前文回顧spring-boot+mybatis+restful api+jwt登陸(1)
用spring-boot開發(fā)RESTful API非常的方便腻格,在生產(chǎn)環(huán)境中悄谐,對發(fā)布的API增加授權(quán)保護(hù)是非常必要的。現(xiàn)在我們來看如何利用JWT技術(shù)為API增加授權(quán)保護(hù),保證只有獲得授權(quán)的用戶才能夠訪問API凯楔。
1. 引入security和jwt依賴
前文已經(jīng)引入了這兩個包,這里再看一下這兩個是如何引入的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
2. 增加注冊功能
利用前文引入的mybatis自動生成代碼的插件锦募,生成model和mapper
- User類摆屯,省略setter和getter方法
public class User {
private String id;
private String username;
private String password;
private String email;
private String mobile;
private String loginIp;
private Date loginTime;
private Byte isAviliable;
private Integer type;
private String avatar;
}
- UserMapper
public interface UserMapper {
int deleteByPrimaryKey(String id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
User findByUsername(String username);
}
插件還會生成對應(yīng)的mapper.xml,具體代碼不再貼出了
創(chuàng)建UserService類糠亩,加入signup方法
@Service
public class UserService {
@Autowired
UserMapper userMapper;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
public User signup(User user) {
user.setId(UUID.randomUUID().toString());
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
userMapper.insertSelective(user);
return user;
}
}
加入控制層代碼
@RestController
@RequestMapping("api/user")
public class UserController {
@Autowired
UserService userService;
@PostMapping(value = "/signup")
public User signup(@RequestBody User user) {
user = userService.signup(user);
return user;
}
}
密碼采用了BCryptPasswordEncoder進(jìn)行加密虐骑,我們在啟動類中增加BCryptPasswordEncoder實例的定義。
@SpringBootApplication
@MapperScan("com.itcuc.qaserver.mapper")
@ServletComponentScan
public class QaserverApplication {
public static void main(String[] args) {
SpringApplication.run(QaserverApplication.class, args);
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
3. 增加jwt認(rèn)證功能
用戶填入用戶名密碼后赎线,與數(shù)據(jù)庫里存儲的用戶信息進(jìn)行比對廷没,如果通>過,則認(rèn)證成功氛驮。傳統(tǒng)的方法是在認(rèn)證通過后,創(chuàng)建sesstion济似,并給客戶端返回cookie〗梅希現(xiàn)在我們采用JWT來處理用戶名密碼的認(rèn)證。區(qū)別在于砰蠢,認(rèn)證通過后蓖扑,服務(wù)器生成一個token,將token返回給客戶端台舱,客戶端以后的所有請求都需要在http頭中指定該token律杠。服務(wù)器接收的請求后,會對token的合法性進(jìn)行驗證竞惋。驗證的內(nèi)容包括:
- 內(nèi)容是一個正確的JWT格式
- 檢查簽名
- 檢查claims
- 檢查權(quán)限
處理登錄
創(chuàng)建一個類JWTLoginFilter柜去,核心功能是在驗證用戶名密碼正確后,生成一個token拆宛,并將token返回給客戶端:
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JWTLoginFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
// 接收并解析用戶憑證
@Override
public Authentication attemptAuthentication(HttpServletRequest req,
HttpServletResponse res) throws AuthenticationException {
try {
User user = new ObjectMapper()
.readValue(req.getInputStream(), User.class);
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
user.getUsername(),
user.getPassword(),
new ArrayList<>())
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// 用戶成功登錄后嗓奢,這個方法會被調(diào)用,我們在這個方法里生成token
@Override
protected void successfulAuthentication(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain,
Authentication auth) throws IOException, ServletException {
String token = Jwts.builder()
.setSubject(((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
.signWith(SignatureAlgorithm.HS512, "MyJwtSecret")
.compact();
res.addHeader("Authorization", "Bearer " + token);
}
}
該類繼承自UsernamePasswordAuthenticationFilter浑厚,重寫了其中的2個方法:
attemptAuthentication
:接收并解析用戶憑證股耽。
successfulAuthentication
:用戶成功登錄后,這個方法會被調(diào)用钳幅,我們在這個方法里生成token物蝙。授權(quán)驗證
用戶一旦登錄成功后,會拿到token敢艰,后續(xù)的請求都會帶著這個token诬乞,服務(wù)端會驗證token的合法性。
創(chuàng)建JWTAuthenticationFilter類,我們在這個類中實現(xiàn)token的校驗功能丽惭。
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token != null) {
// parse the token.
String user = Jwts.parser()
.setSigningKey("MyJwtSecret")
.parseClaimsJws(token.replace("Bearer ", ""))
.getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
}
該類繼承自BasicAuthenticationFilter击奶,在doFilterInternal方法中,從http頭的
Authorization
項讀取token數(shù)據(jù)责掏,然后用Jwts包提供的方法校驗token的合法性柜砾。如果校驗通過,就認(rèn)為這是一個取得授權(quán)的合法請求换衬。SpringSecurity配置
通過SpringSecurity的配置痰驱,將上面的方法組合在一起。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetailsService;
private BCryptPasswordEncoder bCryptPasswordEncoder;
public WebSecurityConfig(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/user/signup").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTLoginFilter(authenticationManager()))
.addFilter(new JWTAuthenticationFilter(authenticationManager()));
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
}
這是標(biāo)準(zhǔn)的SpringSecurity配置內(nèi)容瞳浦,就不在詳細(xì)說明担映。注意其中的
.addFilter(new JWTLoginFilter(authenticationManager()))
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
這兩行,將我們定義的JWT方法加入SpringSecurity的處理流程中叫潦。
(以上內(nèi)容引用自https://blog.csdn.net/sxdtzhaoxinguo/article/details/77965226)
這里需要實現(xiàn)UserDetailsService接口
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private UserMapper userMapper;
/**
* 通過構(gòu)造器注入UserRepository
* @param userMapper
*/
public UserDetailsServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), emptyList());
}
}
這時再請求hello接口蝇完,會返回403錯誤
下面注冊一個新用戶
使用新注冊的用戶登錄,會返回token矗蕊,在http header中短蜕,Authorization: Bearer 后面的部分就是token
然后我們使用這個token再訪問hello接口
至此,功能完成
參考感謝: