前文回顾spring-boot+mybatis+restful api+jwt登陆(1)
用spring-boot开发RESTful API非常的方便,在生产环境中,对发布的API增加授权保护是非常必要的。现在我们来看如何利用JWT技术为API增加授权保护,保证只有获得授权的用户才能够访问API。
1. 引入security和jwt依赖
前文已经引入了这两个包,这里再看一下这两个是如何引入的
<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);
}
插件还会生成对应的mapper.xml,具体代码不再贴出了
创建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进行加密,我们在启动类中增加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认证功能
用户填入用户名密码后,与数据库里存储的用户信息进行比对,如果通>过,则认证成功。传统的方法是在认证通过后,创建sesstion,并给客户端返回cookie。现在我们采用JWT来处理用户名密码的认证。区别在于,认证通过后,服务器生成一个token,将token返回给客户端,客户端以后的所有请求都需要在http头中指定该token。服务器接收的请求后,会对token的合法性进行验证。验证的内容包括:
- 内容是一个正确的JWT格式
- 检查签名
- 检查claims
- 检查权限
处理登录
创建一个类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);
}
}
// 用户成功登录后,这个方法会被调用,我们在这个方法里生成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
:用户成功登录后,这个方法会被调用,我们在这个方法里生成token。授权验证
用户一旦登录成功后,会拿到token,后续的请求都会带着这个token,服务端会验证token的合法性。
创建JWTAuthenticationFilter类,我们在这个类中实现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数据,然后用Jwts包提供的方法校验token的合法性。如果校验通过,就认为这是一个取得授权的合法请求。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);
}
}
这是标准的SpringSecurity配置内容,就不在详细说明。注意其中的
.addFilter(new JWTLoginFilter(authenticationManager()))
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
这两行,将我们定义的JWT方法加入SpringSecurity的处理流程中。
(以上内容引用自https://blog.csdn.net/sxdtzhaoxinguo/article/details/77965226)
这里需要实现UserDetailsService接口
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private UserMapper userMapper;
/**
* 通过构造器注入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接口
至此,功能完成
参考感谢: