认证与授权(二):搭建Spring Cloud Security单体应用

关于认证与授权相关概念介绍,请参考://www.greatytc.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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354