之后会见必要权限央求时附上 Token 进行访谈
分类:网站首页

  创制别的Session(User)的经过要求得到相应Session的Token作为CreateProcessAsUser的参数来运维进度。 

  1. 选用 JWT 做权限验证,比较 Session 的亮点是,Session 须求占用多量服务器内部存款和储蓄器,而且在多服务器时就能波及到分享 Session 难题,在手提式有线电话机等移动端访问时相比较费力
  2. 而 JWT 没有要求存放在服务器,不占用服务器财富,客商在报到后得到 Token 后,访谈必要权限的呼吁时附上 Token(常常设置在Http伏乞头),JWT 不真实多服务器分享的标题,也没有手提式有线话机移动端访谈难点,若为了进步安全,可将 Token 与顾客的 IP 地址绑定起来案例源码下载

  修改有System权限的Token的TokenId为别的Session的TokenId就足以在任何Session里面创造有System权限的进度了。

  相关的Blog: 

  1. 客户通过 AJAX 举行登入获得二个 Token
  2. 事后探访必要权限诉求时附上 Token 实行访问
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="application/javascript"> var header = ""; function login() { $.post("http://localhost:8080/auth/login", { username: $("#username").val(), password: $("#password").val() }, function  { console.log; header = data; }) } function toUserPageBtn() { $.ajax({ type: "get", url: "http://localhost:8080/userpage", beforeSend: function  { request.setRequestHeader("Authorization", header); }, success: function  { console.log; } }); } </script></head><body> <fieldset> <legend>Please Login</legend> <label>UserName</label><input type="text" > <label>Password</label><input type="text" > <input type="button" onclick="login()" value="Login"> </fieldset> <button onclick="toUserPageBtn()">访问UserPage</button></body></html>

思路:

  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; }}

编纂 LoginController,顾客通过客商名、密码访问 /auth/login,通过 LoginDTO 对象抽取,创制一个 Authentication 对象,代码中为 UsernamePasswordAuthenticationToken,决断指标是否存在,通过 AuthenticationManager 的 authenticate 方法对验证对象开展认证,AuthenticationManager 的贯彻类 ProviderManager 会通过 AuthentionProvider 实行验证,暗中同意 ProviderManager 调用 DaoAuthenticationProvider 进行表明处理,DaoAuthenticationProvider 中会通过 UserDetails瑟维斯 获取 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"; }}

本文由网上正规真人赌钱网站发布于网站首页,转载请注明出处:之后会见必要权限央求时附上 Token 进行访谈

上一篇:没有了 下一篇:通过参考官方例程可以很容易实现拥有特定功能
猜你喜欢
热门排行
精彩图文