spring securitySpring Cloud个人学习

认证与授权(二):搭建Spring Cloud Security

2020-05-17  本文已影响0人  JBryan

关于认证与授权相关概念介绍,请参考:https://www.jianshu.com/p/6323a2d63284

数据库新建user表

create table tc_user(
    ID nvarchar (50) not null,
    NAME nvarchar (20) null,
    PWD varchar (50) null,
    ROLE char (5) null,
    SSBM char (5) null,
    PHONE nvarchar (20) null,
    BZ nvarchar (100) null,
    state char (1) null,
    constraint  PK_TC_User primary key (ID asc)
)

新建maven项目,项目结构


项目结构.jpg

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ljessie</groupId>
    <artifactId>control-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>control-security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>8.2.2.jre8</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>


    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

resources文件夹下新建application.yml

spring:
    application:
        name: authorizationServer
    datasource:
        url: jdbc:sqlserver://localhost:1433;instanceName=sql2005;DatabaseName=k_record
        username: sa
        password: 123456
        driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver

server:
    port: 8766

mybatis:
    mapper-locations: classpath:mappers/*.xml
    config-location: classpath:mybatis-config.xml

mybatis-config.xml,mybatis相关配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<!--    mapUnderscoreToCamelCase:开启驼峰命名
        logImpl:控制台打印Sql语句-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>

    <typeAliases>
        <package name="com.ljessie.controlsecurity"/>
    </typeAliases>
</configuration>

ControlSecurityApplication,配置mybatis扫描包注解

package com.ljessie.controlsecurity;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.ljessie.controlsecurity.mapper")
public class ControlSecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(ControlSecurityApplication.class, args);
    }
}

新建实体类User

package com.ljessie.controlsecurity.entity;

import java.util.Set;

public class User {

    private String id;
    private String name;
    private String pwd;
    private String role;

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    /**
     * 用户权限
     */
    private Set<String> authorities;

    public Set<String> getAuthorities() {
        return authorities;
    }

    public void setAuthorities(Set<String> authorities) {
        this.authorities = authorities;
    }

    public User(String id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", password='" + pwd + '\'' +
                ", role='" + role + '\'' +
                ", authorities=" + authorities +
                '}';
    }

    public User() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPpwd(String password) {
        this.pwd = password;
    }
}

新建JsonData用来封装返回的数据

package com.ljessie.controlsecurity.entity;

import java.io.Serializable;

public class JsonData implements Serializable {
    private static final long serialVersionUID = 1L;

    //状态码,0表示成功,-1表示失败
    private int code;
    
    //结果
    private Object data;

    //错误描述
    private String msg;
    
    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public JsonData(int code, Object data) {
        super();
        this.code = code;
        this.data = data;
    }

    public JsonData(int code, String msg, Object data) {
        super();
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
}

新建UserMapper,去数据库查询User

package com.ljessie.controlsecurity.mapper;

import com.ljessie.controlsecurity.entity.User;

public interface UserMapper {

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    User findUserById(String id);
}

resources文件夹下,新建mappers文件夹,再新建UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ljessie.controlsecurity.mapper.UserMapper">
    <select id="findUserById" resultType="User">
        select id,name,pwd,role
            from tc_user
            where id = #{id}
    </select>
</mapper>

然后新建UserService,实现UserDetailsService接口

package com.ljessie.controlsecurity.service;

import com.ljessie.controlsecurity.entity.User;
import com.ljessie.controlsecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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 org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(username)){
            throw new RuntimeException("用户名不能为空");
        }

        User userById = userMapper.findUserById(username);
        if(userById == null){
            throw new RuntimeException("用户不存在");
        }

        //根据用户的角色设置用户的权限
        List<GrantedAuthority> permissions = new ArrayList<>();
        permissions.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return userById.getRole();
            }
        });

        return new org.springframework.security.core.userdetails.User(userById.getId(),userById.getPwd(),permissions);
    }
}

用户表数据:


用户表.jpg

简单起见,UserService里面将role设置为用户拥有的权限。数据库密码保存的是用Spring Security默认的BCryptPasswordEncoder密码编码器哈希过的值,如果是普通的字符串,待会将会报错。新建测试类,生成哈希值,保存到数据库里面。

package com.ljessie.controlsecurity;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCrypt;

@SpringBootTest
class ControlSecurityApplicationTests {

    @Test
    void contextLoads() {
        //对密码进行加密
        String hashpw = BCrypt.hashpw("123456", BCrypt.gensalt());
        System.out.println(hashpw);

        //校验密码
        boolean checkpw = BCrypt.checkpw("123456", "$2a$10$vS1iAP/NFOEu5aB0nIxJY.CRaVclRWqHPy3eCCst3gKMvofLjECEi");
        System.out.println(checkpw);

    }
}

TestPermissionController

package com.ljessie.controlsecurity.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("permission_test")
public class TestPermissionController {

    @RequestMapping("/resource1")
    public String resource1(){
        return "只有00001用户才能访问的资源";
    }

    @RequestMapping("/resource2")
    public String resource2(){
        return "只有00002用户才能访问的资源";
    }
}

配置访问拒绝端点AccessDeniedEntryPoint,当用户没有权限访问资源时,返回自定义的数据。
AccessDeniedEntryPoint

package com.ljessie.controlsecurity.handler;

import com.alibaba.fastjson.JSON;
import com.ljessie.controlsecurity.entity.JsonData;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AccessDeniedEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        JsonData jsonData = new JsonData(-1,"请登录先",null);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(jsonData));
    }
}

配置登录失败处理器,用户登录失败时,返回自定义数据
LoginFailureHandler

package com.ljessie.controlsecurity.handler;

import com.alibaba.fastjson.JSON;
import com.ljessie.controlsecurity.entity.JsonData;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //返回json数据
        JsonData result = null;
        if (e instanceof AccountExpiredException) {
            //账号过期
            result = new JsonData(-1,"账号过期");
        } else if (e instanceof BadCredentialsException) {
            //密码错误
            result = new JsonData(-1,"密码错误");
        } else if (e instanceof CredentialsExpiredException) {
            //密码过期
            result = new JsonData(-1,"密码过期");
        } else if (e instanceof DisabledException) {
            //账号不可用
            result = new JsonData(-1,"账号不可用");
        } else if (e instanceof LockedException) {
            //账号锁定
            result = new JsonData(-1,"账号锁定");
        } else if (e instanceof InternalAuthenticationServiceException) {
            //用户不存在
            result = new JsonData(-1,"用户不存在");
        }else{
            //其他错误
            result = new JsonData(-1,"其他错误");
        }
        //处理编码方式,防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}

登录成功处理器:LoginSuccessHandler

package com.ljessie.controlsecurity.handler;

import com.alibaba.fastjson.JSON;
import com.ljessie.controlsecurity.entity.JsonData;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler{
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        JsonData result = new JsonData(1,"登录成功",principal);
        //处理编码方式,防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}

退出登录处理器:MyLogoutSuccessHandler

package com.ljessie.controlsecurity.handler;

import com.alibaba.fastjson.JSON;
import com.ljessie.controlsecurity.entity.JsonData;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        JsonData result = new JsonData(1,"退出登录");
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}

下面就是Spring Security的核心配置类WebSecurityConfig

package com.ljessie.controlsecurity.config;

import com.ljessie.controlsecurity.handler.AccessDeniedEntryPoint;
import com.ljessie.controlsecurity.handler.LoginFailureHandler;
import com.ljessie.controlsecurity.handler.LoginSuccessHandler;
import com.ljessie.controlsecurity.handler.MyLogoutSuccessHandler;
import com.ljessie.controlsecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AccessDeniedEntryPoint entryPoint;

    @Autowired
    LoginSuccessHandler loginSuccessHandler;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Autowired
    MyLogoutSuccessHandler logoutSuccessHandler;

    /**
     * 密码编辑器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf攻击防御
                .csrf().disable()
                //对路径拦截进行配置
                .authorizeRequests()
                //配置/permission_test/resource1路径需要00001权限
                .antMatchers("/permission_test/resource1").hasAuthority("00001")
                .antMatchers("/permission_test/resource2").hasAuthority("00002")
                //异常处理(权限拒绝,登录失效等)
                .and().exceptionHandling()
                .authenticationEntryPoint(entryPoint)
                //登录
                .and().formLogin()
                .permitAll()
                .successHandler(loginSuccessHandler)//登录成功处理逻辑
                .failureHandler(loginFailureHandler)//登录失败处理逻辑;//允许所有用户;
                //退出登录
                .and().logout().
                permitAll()//允许所有用户
                .logoutSuccessHandler(logoutSuccessHandler)//登出成功处理逻辑
                .deleteCookies("JSESSIONID")  //登出之后删除cookie
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/*").permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //配置认证方式
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    @Bean
    public UserDetailsService userDetailsService(){
        return new UserService();
    }
}

启动应用,使用postman直接访问:http://localhost:8766/permission_test/resource1

test_permission1.jpg
当访问资源被拒绝时,返回自定义的Json数据。
访问Spring Security自带的登录接口http://localhost:8766/login,请求方式为POST,登录role为00001的用户
login_success.jpg
再次访问http://localhost:8766/permission_test/resource1
test_permission_success.jpg
访问resource2接口http://localhost:8766/permission_test/resource2,返回403,role为00001的用户没有权限访问resource2接口
test_permission2.jpg
上一篇 下一篇

猜你喜欢

热点阅读