赞
踩
https://github.com/macrozheng/mall
跳过了官方Learning中较简单的Swagger-UI的实现和整合Redis实现缓存功能的部分,通过整合SpringSecurity和JWT实现后台用户的登录和授权功能,同时改造Swagger-UI的配置使其可以自动记住登录令牌进行发送。
- SpringSecurity是一个强大的可高度定制的认证和授权框架,对于Spring应用来说它是一套Web安全标准。
- SpringSecurity注重于为Java应用提供认证和授权功能,像所有的Spring项目一样,它对自定义需求具有强大的扩展性。
- JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,
- 由于使用了数字签名,所以是可信任和安全的。
{"alg": "HS512"}
{"sub":"admin","created":1489079981393,"exp":1489684781}
- //secret为加密算法的密钥
- String signature = HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE1NTY3NzkxMjUzMDksImV4cCI6MTU1NzM4MzkyNX0.d-iki0193X0bBOETf2UN3r3PotNIEAV7mzIxxeI5IxFyzzkOZxS0PGfF_SK6wxCv2K8S0cZjMkv6b5bCqc0VBw
可以在该网站上获得解析结果:https://jwt.io/
Hutool是一个丰富的Java开源工具包,它帮助我们简化每一行代码,减少每一个方法,mall项目采用了此工具包。
ums_admin
:后台用户表ums_role
:后台用户角色表ums_permission
:后台用户权限表ums_admin_role_relation
:后台用户和角色关系表,用户与角色是多对多关系ums_role_permission_relation
:后台用户角色和权限关系表,角色与权限是多对多关系ums_admin_permission_relation
:后台用户和权限关系表(除角色中定义的权限以外的加减权限),加权限是指用户比角色多出的权限,减权限是指用户比角色少的权限
- <!--SpringSecurity依赖配置-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-security</artifactId>
- </dependency>
- <!--Hutool Java工具包-->
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>4.5.7</version>
- </dependency>
- <!--JWT(Json Web Token)登录支持-->
- <dependency>
- <groupId>io.jsonwebtoken</groupId>
- <artifactId>jjwt</artifactId>
- <version>0.9.0</version>
- </dependency>
- /**
- * 根据用户信息生成token
- */
- public String generateToken(UserDetails userDetails) {
- Map<String, Object> claims = new HashMap<>();
- claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
- claims.put(CLAIM_KEY_CREATED, new Date());
- return generateToken(claims);
- }
-
- /**
- * 根据负责生成JWT的token
- */
- private String generateToken(Map<String, Object> claims) {
- return Jwts.builder()
- .setClaims(claims)
- .setExpiration(generateExpirationDate())
- .signWith(SignatureAlgorithm.HS512, secret)
- .compact();
- }
- /**
- * 从token中获取登录用户名
- */
- public String getUserNameFromToken(String token) {
- String username;
- try {
- Claims claims = getClaimsFromToken(token);
- username = claims.getSubject();
- } catch (Exception e) {
- username = null;
- }
- return username;
- }
- /**
- * 验证token是否还有效
- *
- * @param token 客户端传入的token
- * @param userDetails 从数据库中查询出来的用户信息
- */
- public boolean validateToken(String token, UserDetails userDetails) {
- String username = getUserNameFromToken(token);
- return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
- }
- /**
- * SpringSecurity的配置
- */
- @Configuration
- @EnableWebSecurity
- @EnableGlobalMethodSecurity(prePostEnabled=true)
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Autowired
- private UmsAdminService adminService;
- @Autowired
- private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
- @Autowired
- private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
-
- @Override
- protected void configure(HttpSecurity httpSecurity) throws Exception {
- httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf
- .disable()
- .sessionManagement()// 基于token,所以不需要session
- .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
- .and()
- .authorizeRequests()
- .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
- "/",
- "/*.html",
- "/favicon.ico",
- "/**/*.html",
- "/**/*.css",
- "/**/*.js",
- "/swagger-resources/**",
- "/v2/api-docs/**"
- )
- .permitAll()
- .antMatchers("/admin/login", "/admin/register")// 对登录注册要允许匿名访问
- .permitAll()
- .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
- .permitAll()
- // .antMatchers("/**")//测试时全部运行访问
- // .permitAll()
- .anyRequest()// 除上面外的所有请求全部需要鉴权认证
- .authenticated();
- // 禁用缓存
- httpSecurity.headers().cacheControl();
- // 添加JWT filter
- httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
- //添加自定义未授权和未登录结果返回
- httpSecurity.exceptionHandling()
- .accessDeniedHandler(restfulAccessDeniedHandler)
- .authenticationEntryPoint(restAuthenticationEntryPoint);
- }
- }
- /**
- * 当访问接口没有权限时,自定义的返回结果
- */
- @Component
- public class RestfulAccessDeniedHandler implements AccessDeniedHandler{
- @Override
- public void handle(HttpServletRequest request,
- HttpServletResponse response,
- AccessDeniedException e) throws IOException, ServletException {
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json");
- response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));
- response.getWriter().flush();
- }
- }
- /**
- * 当未登录或者token失效访问接口时,自定义的返回结果
- */
- @Component
- public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
- @Override
- public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json");
- response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
- response.getWriter().flush();
- }
- }
- 在用户名和密码校验前添加的过滤器,如果请求中有jwt的token且有效,会取出token中的用户名,
- 然后调用SpringSecurity的API进行登录操作。
- /**
- * JWT登录授权过滤器
- */
- public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
- private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
- @Autowired
- private UserDetailsService userDetailsService;
- @Autowired
- private JwtTokenUtil jwtTokenUtil;
- @Value("${jwt.tokenHeader}")
- private String tokenHeader;
- @Value("${jwt.tokenHead}")
- private String tokenHead;
-
- @Override
- protected void doFilterInternal(HttpServletRequest request,
- HttpServletResponse response,
- FilterChain chain) throws ServletException, IOException {
- String authHeader = request.getHeader(this.tokenHeader);
- if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
- String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
- String username = jwtTokenUtil.getUserNameFromToken(authToken);
- LOGGER.info("checking username:{}", username);
- if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
- UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
- if (jwtTokenUtil.validateToken(authToken, userDetails)) {
- UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
- authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
- LOGGER.info("authenticated user:{}", username);
- SecurityContextHolder.getContext().setAuthentication(authentication);
- }
- }
- }
- chain.doFilter(request, response);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。