权限验证不迷茫---Spring Security入门-01

一. Spring Security简介

Spring Security是Spring提供的权限验证框架,提供了两大核心功能:

  1. 认证,认证的通俗理解之一就是登录,对用户名密码的认证。当然还有其他的认证方式,例如利用cookie自动登录等。
  2. 授权,授权是对系统资源的保护,针对不同的角色开放不同的资源访问。例如一个管理系统,用户管理,订单管理等系统级别的功能只对系统管理员开放,普通角色只能访问特定的系统功能。

Spring Security围绕这两大核心功能还提供了密码加密、会话管理、csrf防御等功能。

本文定位是Spring Security入门介绍,让读者能对Spring Security有个基本的认识,能够完成认证和授权两大功能的基本配置与开发。

二.开发环境搭建

本文用gradle管理项目,用Spring Boot快速集成Spring Security,具体步骤如下:

1.初始化gradle项目

执行:gradle init,依次选择application,Java,Groovy,JUnit生成java项目

2.搭建Spring Security项目

第一步,分别添加spring-boot,spring-security的依赖,build.gradle文件如下:

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.3.4.RELEASE'
}

repositories {
    jcenter()
}

dependencies {
    testCompile 'junit:junit:4.13'
    
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.3.4.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.3.4.RELEASE'
}

第二步,编写一个最简单的Controller

package com.keepzing.security.controller;

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

@RestController
public class IndexController {
    @GetMapping("/hello")
    public String hello(){
       return "hello, spring security!";
    }
}

第三步,编写Spring Boot启动类

package com.keepzing.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

至此一个最简单的Spring Security集成的web项目就已经完成了

三.Spring Security体验

启动项目,打开上面写的一个简单接口:loaclhost:8080/hello,发现接口无法正常打开,出现如下的画面:
在这里插入图片描述

这说明Spring Security已经生效,项目内所有的路径都被拦截,需要登录后才能访问。Spring Security为用户提供了一个用户名为user的默认用户,密码在日志控制台输出,例如:

Using generated security password: dd5f3c6e-9e09-4c25-91bf-25d0180d10cb

输入用户名和密码即可正常访问接口。

四.Spring Security配置

1.Spring Security配置简介

在Spring Boot中配置Spring Security非常的简单,只需要继承WebSecurityConfigurerAdapter,并且加上EnableWebSecurity注解即可,代码如下:

package com.keepzing.security.configuration;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

}

2.登录用户简单配置

如果使用默认配置,我们只能使用user账号登录,并且每次启动的密码都是不一样的,这样显然时不符合需求的,Spring Security为我们提供了配置接口,只需要覆写WebSecurityConfigurerAdapter中的void configure(AuthenticationManagerBuilder auth)方法,目前我们先用硬编码配置系统中的用户,代码如下:

package com.keepzing.security.configuration;

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;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}123456").roles("USER")
            .and()
            .withUser("admin").password("{noop}123456").roles("ADMIN");
    }
}

这样就配置了两个用户user和admin,密码都为123456,一个角色为USER,另一个为ADMIN(由于Spring Security5之后不支持明文密码,所以加上{noop}作为前缀),这样就完成了简单的Spring Security配置。

3.权限配置

在Spring Boot中使用spring-boot-starter-security依赖,系统默认配置拦截所有请求,允许USER角色用户登录后请求。系统中往往有多种用户,针对不同的角色提供不同的角色拦截,Spring Security提供了简单的配置方式,只需要覆写WebSecurityConfigurerAdapter中的void configure(HttpSecurity http)方法,代码如下:

package com.keepzing.security.configuration;

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;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}123456").roles("USER")
            .and()
            .withUser("admin").password("{noop}123456").roles("ADMIN");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()    //启用表单登录
            .and()
            .authorizeRequests()  //配置角色权限
            .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
            .antMatchers("/admin/**").hasAnyRole("ADMIN")
            .anyRequest().authenticated()   //所有请求都需要登录
        ;
    }
}

经过简单配置就可让USER用户只访问/user/路径,ADMIN用户可以访问/admin/和/user/路径。

五.密码加密

1.介绍

系统中的密码如果直接存储,那样是极大的不安全。往往系统中才用摘要算法,将摘要后的数据存储下来,Spring Security中提供了PasswordEncoder接口用于密码加密与匹配判断。PasswordEncoder主要提供了两个方法:

  1. String encode(CharSequence rawPassword)

    参数rawPassword为未加密的密码,返回值为加密之后的密码

  2. boolean matches(CharSequence rawPassword, String encodedPassword)

    参数rawPassword为未加密的密码,encodedPassword为加密之后的密码,返回值为是否匹配

2.配置

Spring Security中校验密码使用密码验证非常容易,只在IOC容器中注入一个PasswordEncoder实例,系统就会自动使用密码加密与匹配。之前存在内存中的用户密码也需要加密,代码如下:

package com.keepzing.security.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password(passwordEncoder.encode("123456")).roles("USER")
            .and()
            .withUser("admin").password(passwordEncoder.encode("123456")).roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()    //启用表单登录
            .and()
            .authorizeRequests()  //配置角色权限
            .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
            .antMatchers("/admin/**").hasAnyRole("ADMIN")
            .anyRequest().authenticated()   //所有请求都需要登录
        ;
    }

    @Bean //向IOC容器中加入PasswordEncoder实例
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

这里我们采用的是BCryptPasswordEncoder实例,这种加密算法是一种加盐摘要算法,每次加密出的数据都是不一样的,具体加密算法不在本文讨论之列。

六.自定义数据库访问

之前系统中的用户都是用硬编码存储在内存之中,实际项目中的用户数据都是存在数据库当中,Spring Security中为我们提供了接口UserDetailsService和UserDetails接口,用于自定义用户存储。

1.接口简介

  1. UserDetailsService和,接口中只有一个方法:

    UserDetails loadUserByUsername(String username) 根据用户名加载出详细用户信息

  2. UserDetails,是个全是get方法的接口

    UserDetails存储用户的详细信息,包括用户名、密码、角色等。UserDetails是个接口,自定义的PO类可以实现UserDetails接口。

通过UserDetailsService和UserDetails这两个接口就可以轻松与系统

2.实现步骤

使用MyBatis与数据库交互。

  1. 导入MyBatis依赖,在build.gradle的dependencies中加入:

    compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
    compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '2.1.3'
    
  2. 建表,为了方便我们只用一张表存储,多个role用,分开,建表语句如下:

    CREATE TABLE `users` (
    	`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    	`username` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_bin',
    	`password` VARCHAR(60) NOT NULL COLLATE 'utf8mb4_bin',
    	`enable` TINYINT(4) NOT NULL DEFAULT '1',
    	`roles` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    	PRIMARY KEY (`id`) USING BTREE,
    	INDEX `username` (`username`) USING BTREE
    )
    COLLATE='utf8mb4_bin'
    ENGINE=InnoDB
    AUTO_INCREMENT=3;
    

    插入数据,user和admin的密码都是123:

    INSERT INTO `users` (`username`, `password`, `enable`, `roles`) VALUES
    	('user', '$2a$10$qGCMwu0u8GL0QoaKARyg4u8CjesZM00zTDpcfi5gRi5UW5oLytcQ.', 1, 'ROLE_USER'),
    	('admin', '$2a$10$uAtVdnT97YzQhjMYqPDeaO4Wt7iyMtSgBmLf4wne7Ot0e3wULVoee', 1, 'ROLE_ADMIN,ROLE_USER');
    

    实际开发中普遍才用用户、角色和权限三张表。

  3. 实现UserDetails

    package com.keepzing.security.bean;
    
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.AuthorityUtils;
    import org.springframework.security.core.userdetails.UserDetails;
    
    import java.util.Collection;
    
    public class User implements UserDetails {
        private String username;
        private String password;
        private boolean enable;
        private String roles;
    
        public void setUsername(String username) {
            this.username = username;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public void setEnable(boolean enable) {
            this.enable = enable;
        }
        public void setRoles(String roles) {
            this.roles = roles;
        }
        public boolean getEnable() {
            return enable;
        }
        public String getRoles() {
            return roles;
        }
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(roles);
        }
        @Override
        public String getPassword() {
            return password;
        }
        @Override
        public String getUsername() {
            return username;
        }
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
        @Override
        public boolean isEnabled() {
            return enable;
        }
    }
    
    
  4. 实现dao,具体实现如下:

    package com.keepzing.security.dao;
    
    import com.keepzing.security.bean.User;
    import org.apache.ibatis.annotations.Select;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface UserDao {
        @Select("select * from users where username = #{username}")
        User selectUserByUsername(String username);
    }
    
  5. 实现service,代码如下:

    package com.keepzing.security.service;
    
    import org.springframework.security.core.userdetails.UserDetailsService;
    
    public interface UserService extends UserDetailsService { }
    
    package com.keepzing.security.service.impl;
    
    import com.keepzing.security.bean.User;
    import com.keepzing.security.dao.UserDao;
    import com.keepzing.security.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDao userDao;
    
        @Override
        public User loadUserByUsername(String username) throws UsernameNotFoundException {
            return userDao.selectUserByUsername(username);
        }
    }
    
  6. 配置用户配置数据源,配置的方式还是覆写WebSecurityConfigurerAdapter中的void configure(AuthenticationManagerBuilder auth),具体代码如下:

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }
    

    到这就可以使用数据库中的数据进行登录认证数据

七.自定义登录页面

到目前为止,登录页面都是Spring Security提供的默认界面,系统中提供了自定义登录页面的配置方式,覆写WebSecurityConfigurerAdapter中的void configure(AuthenticationManagerBuilder auth)配置自定义页面。

1.编写界面

在resources下建立static目录,然后创建login_page.html页面,代码如下:

<html>
<head>
    <title>login</title>
</head>
<body>
<h1>LOGIN FORM</h1>
<form action="login_page.html" method="post">
    <input type="text" name="username" placeholder="username" /><br/>
    <input type="password" name="password" placeholder="password" /><br/>
    <input type="submit" value="Login">
</form>
</body>
</html>

表单主要需要注意几个点:

  1. 需要用post方式提交,action默认需要与页面名一致,action路径也可以自定义
  2. 表单中需要有username、password字段
  3. 如果开启csrf验证需要_csrf隐藏字段,_csrf需要用Spring Security提供的标签生成,目前禁用csrf不需要这个字段

2.配置登录页面

配置首页在void configure(HttpSecurity http)方法中配置,代码如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
        .loginPage("/login_page.html")  //配置首页地址
        .permitAll()    //配置页面不需要登录可以直接访问
        .and()
        .csrf().disable()   //禁用csrf验证
        .authorizeRequests()  //配置角色权限
        .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
        .antMatchers("/admin/**").hasAnyRole("ADMIN")
        .anyRequest().authenticated()   //所有请求都需要登录
        ;
}

这样就可以实现使用自定义的登录页面,如果表单需要使用自定义的action地址,需要这样配置loginPage("/login_page.html").loginProcessingUrl("/my_login").permitAll(),表单中改成action="/my_login"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值