Spring Security 结合 JWT

  修改有System权限的Token的TokenId为另外Session的TokenId就足以在其余Session里面创立有System权限的经过了。

  相关的Blog: 

  创设别的Session(User)的进度须要得到相应Session的Token作为CreateProcessAsUser的参数来运维进程。 

思路:

  1. 创办客商、权限实体类与数码传输对象

  2. 编纂 Dao 层接口,用于获取客户新闻

  3. 福寿无疆 UserDetails(Security 扶植的客户实体对象,饱含权限消息)

  4. 落实UserDetailsSevice(从数据库中收获顾客信息,并打包成UserDetails)

  5. 编纂 JWTToken 生成工具,用于转移、验证、分析 Token

  6. 配备 Security,配置诉求管理 与 设置 UserDetails 获取格局为自定义的 UserDetailsSevice

  7. 编写制定 LoginController,接收客商登入名密码并拓宽认证,若验证成功重回Token 给客商

  8. 编写过滤器,若客商央浼头或参数中包蕴 Token 则剖判,并生成 Authentication,绑定到 SecurityContext ,供 Security 使用

  9. 客户访谈了要求权限的页面,却没附上精确的 Token,在过滤器管理时则从未生成 Authentication,也就不真实访谈权限,则不可能访谈,否之访问成功

User实体类

@Data@Entitypublic class User { @Id @GeneratedValue private int id; private String name; private String password; @ManyToMany(cascade = {CascadeType.REFRESH}, fetch = FetchType.EAGER) @JoinTable(name = "user_role", joinColumns = {@JoinColumn(name = "uid", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "rid", referencedColumnName = "id")}) private List<Role> roles;} 

Role实体类

@Data@Entitypublic class Role { @Id @GeneratedValue private int id; private String name; @ManyToMany(mappedBy = "roles") private List<User> users;}

安顿数据

User 表

id name password
1 linyuan 123

Role 表

id name
1 USER

User_ROLE 表

uid rid
1 1

Dao 层接口,通过顾客名获取数据,重返值为 Java8 的 Optional 对象

public interface UserRepository extends Repository<User,Integer> { Optional<User> findByName(String name);}

编写制定 LoginDTO,用于与前面三个之间数据传输

@Datapublic class LoginDTO implements Serializable { @NotBlank(message = "用户名不能为空") private String username; @NotBlank(message = "密码不能为空") private String password;}

编纂 Token 生成工具,利用 JJWT 库创制,一共七个议程:生成 Token、分析Token(重临Authentication认证对象)、验证 Token

@Componentpublic class JWTTokenUtils { private final Logger log = LoggerFactory.getLogger(JWTTokenUtils.class); private static final String AUTHORITIES_KEY = "auth"; private String secretKey; //签名密钥 private long tokenValidityInMilliseconds; //失效日期 private long tokenValidityInMillisecondsForRememberMe; //失效日期 @PostConstruct public void init() { this.secretKey = "Linyuanmima"; int secondIn1day = 1000 * 60 * 60 * 24; this.tokenValidityInMilliseconds = secondIn1day * 2L; this.tokenValidityInMillisecondsForRememberMe = secondIn1day * 7L; } private final static long EXPIRATIONTIME = 432_000_000; //创建Token public String createToken(Authentication authentication, Boolean rememberMe){ String authorities = authentication.getAuthorities().stream() //获取用户的权限字符串,如 USER,ADMIN .map(GrantedAuthority::getAuthority) .collect(Collectors.joining; long now = (new Date.getTime(); //获取当前时间戳 Date validity; //存放过期时间 if (rememberMe){ validity = new Date(now + this.tokenValidityInMilliseconds); }else { validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } return Jwts.builder() //创建Token令牌 .setSubject(authentication.getName //设置面向用户 .claim(AUTHORITIES_KEY,authorities) //添加权限属性 .setExpiration //设置失效时间 .signWith(SignatureAlgorithm.HS512,secretKey) //生成签名 .compact(); } //获取用户权限 public Authentication getAuthentication(String token){ System.out.println("token:"+token); Claims claims = Jwts.parser() //解析Token的payload .setSigningKey(secretKey) .parseClaimsJws .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split //获取用户权限字符串 .map(SimpleGrantedAuthority::new) .collect(Collectors.toList; //将元素转换为GrantedAuthority接口集合 User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); } //验证Token是否正确 public boolean validateToken(String token){ try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws; //通过密钥验证Token return true; }catch (SignatureException e) { //签名异常 log.info("Invalid JWT signature."); log.trace("Invalid JWT signature trace: {}", e); } catch (MalformedJwtException e) { //JWT格式错误 log.info("Invalid JWT token."); log.trace("Invalid JWT token trace: {}", e); } catch (ExpiredJwtException e) { //JWT过期 log.info("Expired JWT token."); log.trace("Expired JWT token trace: {}", e); } catch (UnsupportedJwtException e) { //不支持该JWT log.info("Unsupported JWT token."); log.trace("Unsupported JWT token trace: {}", e); } catch (IllegalArgumentException e) { //参数错误异常 log.info("JWT token compact of handler are invalid."); log.trace("JWT token compact of handler are invalid trace: {}", e); } return false; }}

贯彻 UserDetails 接口,代表客户实体类,在我们的 User 对象上在展开包装,包涵了权力等天性,能够供 Spring Security 使用

public class MyUserDetails implements UserDetails{ private User user; public MyUserDetails(User user) { this.user = user; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<Role> roles = user.getRoles(); List<GrantedAuthority> authorities = new ArrayList<>(); StringBuilder sb = new StringBuilder(); if (roles.size{ for (Role role : roles){ authorities.add(new SimpleGrantedAuthority(role.getName; } return authorities; } return AuthorityUtils.commaSeparatedStringToAuthorityList; } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getName(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; }}

贯彻 UserDetailsService 接口,该接口独有四个办法,用来获得UserDetails,大家能够从数据库中得到 User 对象,然后将其卷入成 UserDetails 并再次回到

@Servicepublic class MyUserDetailsService implements UserDetailsService { @Autowired UserRepository userRepository; @Override public UserDetails loadUserByUsername throws UsernameNotFoundException { //从数据库中加载用户对象 Optional<User> user = userRepository.findByName; //调试用,如果值存在则输出下用户名与密码 user.ifPresent->System.out.println("用户名:"+value.getName()+" 用户密码:"+value.getPassword; //若值不再则返回null return new MyUserDetails(user.orElse; }}

编写制定过滤器,顾客一旦带领 Token 则收获 Token,并基于 Token 生成 Authentication 认证对象,并贮存到 SecurityContext 中,供 Spring Security 进行权力调控

public class JwtAuthenticationTokenFilter extends GenericFilterBean { private final Logger log = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class); @Autowired private JWTTokenUtils tokenProvider; @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("JwtAuthenticationTokenFilter"); try { HttpServletRequest httpReq = (HttpServletRequest) servletRequest; String jwt = resolveToken; if (StringUtils.hasText && this.tokenProvider.validateToken { //验证JWT是否正确 Authentication authentication = this.tokenProvider.getAuthentication; //获取用户认证信息 SecurityContextHolder.getContext().setAuthentication(authentication); //将用户保存到SecurityContext } filterChain.doFilter(servletRequest, servletResponse); }catch (ExpiredJwtException e){ //JWT失效 log.info("Security exception for user {} - {}", e.getClaims().getSubject(), e.getMessage; log.trace("Security exception trace: {}", e); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } private String resolveToken(HttpServletRequest request){ String bearerToken = request.getHeader(WebSecurityConfig.AUTHORIZATION_HEADER); //从HTTP头部获取TOKEN if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){ return bearerToken.substring(7, bearerToken.length; //返回Token字符串,去除Bearer } String jwt = request.getParameter(WebSecurityConfig.AUTHORIZATION_TOKEN); //从请求参数中获取TOKEN if (StringUtils.hasText { return jwt; } return null; }}

2020欧洲杯官方投注-2020欧洲杯官方投注网址,编写制定 LoginController,客商通过客户名、密码访谈 /auth/login,通过 LoginDTO 对象摄取,创造三个 Authentication 对象,代码中为 UsernamePasswordAuthenticationToken,剖断目标是还是不是留存,通过 AuthenticationManager 的 authenticate 方法对认证对象开展验证,AuthenticationManager 的实现类 ProviderManager 会通过 AuthentionProvider 举办表达,暗中认可 ProviderManager 调用 DaoAuthenticationProvider 实行表明处理,DaoAuthenticationProvider 中会通过 UserDetailsService 获取 UserDetails ,若表明成功则赶回一个含有权限的 Authention,然后经过 SecurityContextHolder.getContext().setAuthentication() 设置到 SecurityContext 中,依照 Authentication 生成 Token,并赶回给客商

@RestControllerpublic class LoginController { @Autowired private UserRepository userRepository; @Autowired private AuthenticationManager authenticationManager; @Autowired private JWTTokenUtils jwtTokenUtils; @RequestMapping(value = "/auth/login",method = RequestMethod.POST) public String login(@Valid LoginDTO loginDTO, HttpServletResponse httpResponse) throws Exception{ //通过用户名和密码创建一个 Authentication 认证对象,实现类为 UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDTO.getUsername(),loginDTO.getPassword; //如果认证对象不为空 if (Objects.nonNull(authenticationToken)){ userRepository.findByName(authenticationToken.getPrincipal().toString .orElseThrow->new Exception; } try { //通过 AuthenticationManager(默认实现为ProviderManager)的authenticate方法验证 Authentication 对象 Authentication authentication = authenticationManager.authenticate(authenticationToken); //将 Authentication 绑定到 SecurityContext SecurityContextHolder.getContext().setAuthentication(authentication); //生成Token String token = jwtTokenUtils.createToken(authentication,false); //将Token写入到Http头部 httpResponse.addHeader(WebSecurityConfig.AUTHORIZATION_HEADER,"Bearer "+token); return "Bearer "+token; }catch (BadCredentialsException authentication){ throw new Exception; } }}

编写 Security 配置类,继承 WebSecurityConfigurerAdapter,重写 configure 方法

@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public static final String AUTHORIZATION_HEADER = "Authorization"; public static final String AUTHORIZATION_TOKEN = "access_token"; @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth //自定义获取用户信息 .userDetailsService(userDetailsService) //设置密码加密 .passwordEncoder(passwordEncoder; } @Override protected void configure(HttpSecurity http) throws Exception { //配置请求访问策略 http //关闭CSRF、CORS .cors().disable.disable() //由于使用Token,所以不需要Session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() //验证Http请求 .authorizeRequests() //允许所有用户访问首页 与 登录 .antMatchers("/","/auth/login").permitAll() //其它任何请求都要经过认证通过 .anyRequest().authenticated() //用户页面需要用户权限 .antMatchers("/userpage").hasAnyRole .and() //设置登出 .logout().permitAll(); //添加JWT filter 在 http .addFilterBefore(genericFilterBean(), UsernamePasswordAuthenticationFilter.class); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public GenericFilterBean genericFilterBean() { return new JwtAuthenticationTokenFilter(); }}

编写用于测量检验的Controller

@RestControllerpublic class UserController { @PostMapping public String login() { return "login"; } @GetMapping public String index() { return "hello"; } @GetMapping("/userpage") public String httpApi() { System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal; return "userpage"; } @GetMapping("/adminpage") public String httpSuite() { return "userpage"; }}

本文由2020欧洲杯官方投注-2020欧洲杯官方投注网址发布于win7,转载请注明出处:Spring Security 结合 JWT

相关阅读