• Spring Security


    一、Spring Security介绍

    1、框架介绍

    Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证Authentication)和用户授权(Authorization两个部分。

    (1)用户认证指的是:验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。

    (2)用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

    Spring Security其实就是用filter,多请求的路径进行过滤。

    (1)如果是基于Session,那么Spring-security会对cookie里的sessionid进行解析,找到服务器存储的sesion信息,然后判断当前用户是否符合请求的要求。

    (2)如果是token,则是解析出token,然后将当前请求加入到Spring-security管理的权限信息中去

    2、认证与授权实现思路

    如果系统的模块众多,每个模块都需要就行授权与认证,所以我们选择基于token的形式进行授权与认证,用户根据用户名密码认证成功,然后获取当前用户角色的一系列权限值,并以用户名为key,权限列表为value的形式存入redis缓存中,根据用户名相关信息生成token返回,浏览器将token记录到cookie中,每次调用api接口都默认将token携带到header请求头中,Spring-security解析header头获取token信息,解析token获取当前用户名,根据用户名就可以从redis中获取权限列表,这样Spring-security就能够判断当前请求是否有权限访问

    3、认证与授权实现思路图解

    二、代码示例

    1、pom依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>common</artifactId>
            <groupId>com.stu</groupId>
            <version>0.0.1-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>spring_security</artifactId>
        <dependencies>
            <!-- Spring Security依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
    
            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt</artifactId>
            </dependency>
        </dependencies>
    
    </project>

    目录结构

    2、Spring Security的核心配置就是继承WebSecurityConfigurerAdapter并注解@EnableWebSecurity的配置。这个配置指明了用户名密码的处理方式、请求路径的开合、登录登出控制等和安全相关的配置

    package com.stu.security.config;
    
    import com.stu.security.filter.TokenAuthenticationFilter;
    import com.stu.security.filter.TokenLoginFilter;
    import com.stu.security.security.DefaultPasswordEncoder;
    import com.stu.security.security.TokenLogoutHandler;
    import com.stu.security.security.TokenManager;
    import com.stu.security.security.UnauthorizedEntryPoint;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.UserDetailsService;
    
    /**
     * <p>
     * Security配置类
     * </p>
     *
     * @author qy
     * @since 2019-11-18
     */
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        private UserDetailsService userDetailsService;
        private TokenManager tokenManager;
        private DefaultPasswordEncoder defaultPasswordEncoder;
        private RedisTemplate redisTemplate;
    
        @Autowired
        public TokenWebSecurityConfig(UserDetailsService userDetailsService, DefaultPasswordEncoder defaultPasswordEncoder,
                                      TokenManager tokenManager, RedisTemplate redisTemplate) {
            this.userDetailsService = userDetailsService;
            this.defaultPasswordEncoder = defaultPasswordEncoder;
            this.tokenManager = tokenManager;
            this.redisTemplate = redisTemplate;
        }
    
        /**
         * 配置设置
         * @param http
         * @throws Exception
         */
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.exceptionHandling()
                    .authenticationEntryPoint(new UnauthorizedEntryPoint())
                    .and().csrf().disable()
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and().logout().logoutUrl("/admin/acl/index/logout")
                    .addLogoutHandler(new TokenLogoutHandler(tokenManager,redisTemplate)).and()
                    .addFilter(new TokenLoginFilter(authenticationManager(), tokenManager, redisTemplate))
                    .addFilter(new TokenAuthenticationFilter(authenticationManager(), tokenManager, redisTemplate)).httpBasic();
        }
    
        /**
         * 密码处理
         * @param auth
         * @throws Exception
         */
        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
        }
    
        /**
         * 配置哪些请求不拦截
         * @param web
         * @throws Exception
         */
        @Override
        public void configure(WebSecurity web) throws Exception {
    //        web.ignoring().antMatchers("/api/**",
    //                "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"
    //               );
            web.ignoring().antMatchers("/*/**"
            );
        }
    }

    3、认证授权实体类

    SecurityUser类

    package com.stu.security.entity;
    
    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.util.StringUtils;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    /**
     * <p>
     * 安全认证用户详情信息
     * </p>
     *
     * @author qy
     * @since 2019-11-08
     */
    @Data
    @Slf4j
    public class SecurityUser implements UserDetails {
    
        //当前登录用户
        private transient User currentUserInfo;
    
        //当前权限
        private List<String> permissionValueList;
    
        public SecurityUser() {
        }
    
        public SecurityUser(User user) {
            if (user != null) {
                this.currentUserInfo = user;
            }
        }
    
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            for(String permissionValue : permissionValueList) {
                if(StringUtils.isEmpty(permissionValue)) continue;
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
                authorities.add(authority);
            }
    
            return authorities;
        }
    
        @Override
        public String getPassword() {
            return currentUserInfo.getPassword();
        }
    
        @Override
        public String getUsername() {
            return currentUserInfo.getUsername();
        }
    
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
    
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
    
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
    
        @Override
        public boolean isEnabled() {
            return true;
        }
    }

    User类

    package com.stu.security.entity;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    import java.io.Serializable;
    
    /**
     * <p>
     * 用户实体类
     * </p>
     *
     * @author qy
     * @since 2019-11-08
     */
    @Data
    @ApiModel(description = "用户实体类")
    public class User implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @ApiModelProperty(value = "微信openid")
        private String username;
    
        @ApiModelProperty(value = "密码")
        private String password;
    
        @ApiModelProperty(value = "昵称")
        private String nickName;
    
        @ApiModelProperty(value = "用户头像")
        private String salt;
    
        @ApiModelProperty(value = "用户签名")
        private String token;
    
    }

    4、TokenLoginFilter:认证的filter

    package com.stu.security.filter;
    
    import com.stu.commonutils.ResultData;
    import com.stu.commonutils.ResponseUtil;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.stu.security.entity.SecurityUser;
    import com.stu.security.entity.User;
    import com.stu.security.security.TokenManager;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.ArrayList;
    
    /**
     * <p>
     * 登录过滤器,继承UsernamePasswordAuthenticationFilter,对用户名密码进行登录校验
     * </p>
     *
     * @author qy
     * @since 2019-11-08
     */
    public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    
        private AuthenticationManager authenticationManager;
        private TokenManager tokenManager;
        private RedisTemplate redisTemplate;
    
        public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
            this.authenticationManager = authenticationManager;
            this.tokenManager = tokenManager;
            this.redisTemplate = redisTemplate;
            this.setPostOnly(false);
            this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login","POST"));
        }
    
        @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);
            }
    
        }
    
        /**
         * 登录成功
         * @param req
         * @param res
         * @param chain
         * @param auth
         * @throws IOException
         * @throws ServletException
         */
        @Override
        protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                                Authentication auth) throws IOException, ServletException {
            SecurityUser user = (SecurityUser) auth.getPrincipal();
            String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
            redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList());
    
            ResponseUtil.out(res, ResultData.success().data("token", token));
        }
    
        /**
         * 登录失败
         * @param request
         * @param response
         * @param e
         * @throws IOException
         * @throws ServletException
         */
        @Override
        protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                  AuthenticationException e) throws IOException, ServletException {
            ResponseUtil.out(response, ResultData.error());
        }
    }

    5、TokenAuthenticationFilter

    package com.stu.security.filter;
    
    import com.stu.commonutils.ResultData;
    import com.stu.commonutils.ResponseUtil;
    import com.stu.security.security.TokenManager;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
    import org.springframework.util.StringUtils;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    /**
     * <p>
     * 访问过滤器
     * </p>
     *
     * @author qy
     * @since 2019-11-08
     */
    public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
        private TokenManager tokenManager;
        private RedisTemplate redisTemplate;
    
        public TokenAuthenticationFilter(AuthenticationManager authManager, TokenManager tokenManager,RedisTemplate redisTemplate) {
            super(authManager);
            this.tokenManager = tokenManager;
            this.redisTemplate = redisTemplate;
        }
    
        @Override
        protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
                throws IOException, ServletException {
            logger.info("================="+req.getRequestURI());
            if(req.getRequestURI().indexOf("admin") == -1) {
                chain.doFilter(req, res);
                return;
            }
    
            UsernamePasswordAuthenticationToken authentication = null;
            try {
                authentication = getAuthentication(req);
            } catch (Exception e) {
                ResponseUtil.out(res, ResultData.error());
            }
    
            if (authentication != null) {
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } else {
                ResponseUtil.out(res, ResultData.error());
            }
            chain.doFilter(req, res);
        }
    
        private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
            // token置于header里
            String token = request.getHeader("token");
            if (token != null && !"".equals(token.trim())) {
                String userName = tokenManager.getUserFromToken(token);
    
                List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(userName);
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                for(String permissionValue : permissionValueList) {
                    if(StringUtils.isEmpty(permissionValue)) continue;
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
                    authorities.add(authority);
                }
    
                if (!StringUtils.isEmpty(userName)) {
                    return new UsernamePasswordAuthenticationToken(userName, token, authorities);
                }
                return null;
            }
            return null;
        }
    }

    6、UserDetailsServiceImpl类

    package com.stu.aclservice.service.impl;
    
    import com.stu.aclservice.entity.User;
    import com.stu.aclservice.service.PermissionService;
    import com.stu.aclservice.service.UserService;
    import com.stu.security.entity.SecurityUser;
    import org.springframework.beans.BeanUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    
    /**
     * <p>
     * 自定义userDetailsService - 认证用户详情
     * </p>
     *
     * @author qy
     * @since 2019-11-08
     */
    @Service("userDetailsService")
    public class UserDetailsServiceImpl implements UserDetailsService {
    
        @Autowired
        private UserService userService;
    
        @Autowired
        private PermissionService permissionService;
    
        /***
         * 根据账号获取用户信息
         * @param username:
         * @return: org.springframework.security.core.userdetails.UserDetails
         */
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            // 从数据库中取出用户信息
            User user = userService.selectByUsername(username);
    
            // 判断用户是否存在
            if (null == user){
                //throw new UsernameNotFoundException("用户名不存在!");
            }
            // 返回UserDetails实现类
            com.stu.security.entity.User curUser = new com.stu.security.entity.User();
            BeanUtils.copyProperties(user,curUser);
    
            List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
            SecurityUser securityUser = new SecurityUser(curUser);
            securityUser.setPermissionValueList(authorities);
            return securityUser;
        }
    
    }

    7、图解

  • 相关阅读:
    一个简单而经典的RTX51 Tiny应用实例
    基于HttpClient 4.3的可訪问自签名HTTPS网站的新版工具类
    动态绑定与动态分发-动态绑定暗含动态分发
    多态是面向接口编程的概念
    多态本质:多个对象共享同一接口 多态本质是共享接口
    Smalltalk
    Simula-Virtual function
    执行力
    目标、计划:下定决心 排除万难
    当断不断,必受其乱
  • 原文地址:https://www.cnblogs.com/konglxblog/p/15173789.html
Copyright © 2020-2023  润新知