也没有手机移动端访问问题

作者:金沙总站6155

澳门娱乐6165,  成立其余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 中会通过 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"; }}

本文由澳门娱乐6165发布,转载请注明来源

关键词: