SpringSecurity

一、导入依赖:

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

二、在yml中设置自定义密码:

spring:
  security:
    user:
      name: user
      password: 1234

三、排除Security和数据源的自动配置

@SpringBootApplication(exclude = {
       DataSourceAutoConfiguration.class, SecurityAutoConfiguration.class
})

四、使用内存中的用户信息

使用WebSecurityConfigurerAdapter 控制安全管理的内容。

需要做的使用: 继承WebSecurityConfigurerAdapter ,重写方法。实现自定义的认证信息。

spring security5 版本要求密码必须加密,否则报错

基于方法级别角色认证的实现步骤:

1.设置用户的角色

继承WebSecurityConfigurerAdapter ,重写configure方法。指定角色和用户信息。

2.在类的上面加入启用方法级别的注解,@EnableGlobalMethodSecurity(prePostEnabled = true)

3.在处理器方法的上面加入角色的信息,指定方法可以访问的角色列表,使用   // 通过@PreAuthorize(value = "hasAnyRole('角色名称1','角色名称N')")指定在方法之前进行角色的认证。

1)添加用户信息,设置角色

/**
         * @EnableGlobalMethodSecurity:启用方法级别的认证 
         *      prePostEnabled:Boolean 默认是false
         *          true:表示可以使用@PreAuthorize注解和 @PostAuthorize
         *          
         * @EnableWebSecurity//表示启用spring security安全框架功能
         * 
         * @Configuration//表示当前类是一 个配置类(相当于是spring的xml配置文件) , 在这个类方法的返回值是java 对象,这些对象放入到spring容器中
         */


        @EnableWebSecurity//表示启用spring security安全框架功能

        @Configuration//表示当前类是一 个配置类(相当于是spring的xml配置文件) , 在这个类方法的返回值是java 对象,这些对象放入到spring容器中
        @EnableGlobalMethodSecurity(prePostEnabled = true)

        public class RainSecurityConfig extends WebSecurityConfigurerAdapter {

            // 在方法中配置 用户和密码的信息,作为登录的数据
            protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                PasswordEncoder pe = passwordEncoder();//调用加密方法,返回一个加密类
                auth.inMemoryAuthentication().
                        withUser("rain")
                        .password(pe.encode("2233"))//对明文密码进行加密
                        .roles("normal");//设置角色

                auth.inMemoryAuthentication()
                        .withUser("admin")
                        .password(pe.encode("admin"))
                        .roles("admin");//设置角色

            }

            // 创建密码的加密类
            @Bean
            public PasswordEncoder passwordEncoder() {
                // 创建PasswordEncoder的实现类, 实现类是加密算法
                return new BCryptPasswordEncoder();
            }

        }

 2)设置不同角色权限的方法

        // 通过@PreAuthorize(value = "hasAnyRole('角色名称1','角色名称N')")指定那些角色可以访问的哪些方法
        @PreAuthorize(value = "hasAnyRole('admin','normal')")
        @GetMapping("/normal")
        public String normalAndAdminMethod() {
            return "normal and admin";
        }

        // 指定只有admin可以访问
        @PreAuthorize("hasAnyRole('admin')")
        @GetMapping("/admin")
        public String adminMethod() {
            return "admin";
        }

基于JDBC(数据库)的用户认证(这里开始才是重点)

在spring security框架对象中用户信息的表示类是UserDetails

UserDetails 是一个接口,高度抽象的用户信息类(相当于项目中的User类)

一、实现UserDetailsService接口,重写UserDetailsByUsername(String var1),在方法中获取数据库中的用户信息,条件是用户名称

package com.example.springsecurity.provider;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springsecurity.dao.UserInfoDao;
import com.example.springsecurity.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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.Component;

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


@Component("MyUserDetailService")//定义一个为标识
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserInfoDao userInfoDao;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = null;
        User user = null;
        if (username != null) {
            LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //三个参数,第一个参数是判断连不连查询条件,true就连查询条件,flase就不连查询条件,第二个是字段名,第三个参数是条件值
            lambdaQueryWrapper.eq(UserInfo::getName, username);
            userInfo = userInfoDao.selectOne(lambdaQueryWrapper);
            if (userInfo != null) {
                //创建一个List,用于存放查出的用户角色
                List<GrantedAuthority> list = new ArrayList<>();
                //将查询到的角色信息放入SimpleGrantedAuthority()中,角色必须以ROLE_开头
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + userInfo.getRole());
                list.add(authority);

                //创建User对象(框架的)
                user = new User(userInfo.getName(), userInfo.getPassword(), list);
            }
        }

        return user;
    }
}

二、在自定义配置类中使用

package com.example.springsecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
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.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;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("MyUserDetailService")
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

}

三、在方法上中使用注解

  @PreAuthorize("hasAnyRole('normal','admin')")//这是设置需要什么角色才能访问
    @RequestMapping("/normal")
    public String normal(){
        return "normal and admin";
    }
 
    @PreAuthorize("hasAnyRole('admin')")
    @RequestMapping("/admin")
    public String admin(){
        return "admin";
    }

RBAC设计中的表:

  1. 用户表:用户认证(登录用到的表)
    1. 用户名,密码,是否启用,是否锁定等信息。
  2. 角色表:定义角色信息
    1. 角色名称,角色的描述。←
  3. 用户和角色的关系表:用户和角色是多对多的关系。
    1. 一个用户可以有多个角色,一个角色可以有多个用户。
  4. 权限表,角色和权限的关系表
    1. 角色可以有哪些权限。
       

实现步骤:

  1. 新建maven项目
  2. 加入maven坐标
    1. spring-boot 
    2. spring-security
    3. spring-web
    4. spring和mybatis-puls相关的依赖
    5.  mysql驱动
  3. 编写application.properties
    1. 连接数据库,创建连接池
  4. 创建实体类
    1. 定义用户信息类,实现 spring security 框架中的 UserDetails.
    2. 角色类,
  5. 编写Mapper 类
  6. 创建service自定义类实现UserDetatilsService类
    1.   在重写方法中,查询数据库获取用户信息, 获取角色数据。
  7. 创建 Controlle
    1. 1.IndexController : 转发到首页 index.htm(主要为了设置进入首页不需要身份认证)
    2. .MyController
  8. 创建config类继承WebSecurityConfigurerAdapter
    1.  自定义安全的配置
    2. 注入自定义的 UserDetatilsServic
  9. 自定义登录
    1. 传统form登录
    2. ajax登录
  10. 创建Controller

一、创建实体类

1)定义用户信息类,实现 spring security 框架中的 UserDetails.

package com.example.user_role_ajax.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Date;
import java.util.List;


@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "user")
public class User implements UserDetails {

    private int id;
    private String name;
    private String password;
    private String realname;
    private boolean inenable;//是否启用
    private boolean islock;///是否锁定
    private boolean iscredentials;//凭证
    private boolean isexpired;//是否过期
    private Date createtime;//创建时间
    private Date logintime;//登入时间
    private List<GrantedAuthority> authorities;

    public User(String name, String password, String realname, boolean inenable, boolean islock,
                boolean iscredentials, boolean isexpired, Date createtime, Date logintime,
                List<GrantedAuthority> authorities) {
        this.name = name;
        this.password = password;
        this.realname = realname;
        this.inenable = inenable;
        this.islock = islock;
        this.iscredentials = iscredentials;
        this.isexpired = isexpired;
        this.createtime = createtime;
        this.logintime = logintime;
        this.authorities = authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return name;
    }

    @Override
    public boolean isAccountNonExpired() {
        return isexpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return islock;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return iscredentials;
    }

    @Override
    public boolean isEnabled() {
        return inenable;
    }
}

2)角色类

package com.example.user_role_ajax.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "role")
public class Role {
    private Integer id;
    private String rolename;
    private String rolememo;
}

二、编写Mapper 类

1)RoleMapper 

package com.example.user_role_ajax.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.user_role_ajax.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;


@Mapper
public interface RoleMapper extends BaseMapper<Role> {

    @Select("select r.id,r.rolename,r.rolememo from  user_role ur,role r where ur.roleid=r.id and ur.userid=#{userId}")
    List<Role> selectRoleByUser(Integer userId);
}

2)UserMapper

package com.example.user_role_ajax.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.user_role_ajax.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper extends BaseMapper<User> {
    @Insert("insert into user(name,password,realname,inenable,isexpired,islock,iscredentials,createtime,logintime) values " +
            "(#{name},#{password},#{realname},#{inenable},#{isexpired},#{islock},#{iscredentials},#{createtime},#{logintime})")
    int insertUser(User user);

    @Select("select id,name,password,realname,inenable,islock,iscredentials,isexpired,createtime,logintime from user where " +
            "name=#{username}")
    User selectUser(String username);
}

三、创建自定义的UserDetatilsService实现类

在重写方法中,查询数据库获取用户信息, 获取角色数据。

package com.example.user_role_ajax.service;


import com.example.user_role_ajax.entity.Role;
import com.example.user_role_ajax.entity.User;
import com.example.user_role_ajax.mapper.RoleMapper;
import com.example.user_role_ajax.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.ArrayList;
import java.util.List;

@Service
public class JdbcUserDetatilsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据username,获取用户信息
        User user = userMapper.selectUser(username);

        if (user != null) {
            //2.根据userId ,获取角色信息
            List<Role> roles = roleMapper.selectRoleByUser(user.getId());
            //创建一个存储role的集合
            List<GrantedAuthority> authorityList = new ArrayList<>();
            String rolename = "";
            for (Role role : roles) {
                rolename = role.getRolename();
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + rolename);
                authorityList.add(authority);
            }
            user.setAuthorities(authorityList);
            return user;
        }
        return user;
    }
}

五、创建 Controlle

1)IndexController : 转发到首页 index.htm(主要为了设置进入首页不需要身份认证)

package com.example.user_role_ajax.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;


@Controller
public class IndexController {
    @GetMapping("/index")
    public String toIndexHtml() {
        return "forward:/index.html";
    }
}

2)MyController

package com.example.user_role_ajax.controller;


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

@RestController
public class MyControler {
    @RequestMapping(value = "/access/user", produces = "text/html;charset=utf-8")
    public String sayuser() {
        return "za 是USER";
    }

    @RequestMapping(value = "/access/read", produces = "text/html;charset=utf-8")
    public String sayread() {
        return "lisi 是READ";
    }

    @RequestMapping(value = "/access/admin", produces = "text/html;charset=utf-8")
    public String sayadmin() {
        return "admin 是admin";
    }

}

六、创建config类继承WebSecurityConfigurerAdapter

 自定义安全的配置,注入自定义的 UserDetatilsServic

package com.example.user_role_ajax.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
public class configCustomSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationSuccessHandler successHandler;
    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //   super.configure(auth);
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    //设置首页不需要认证
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                //设置访问的白名单,无需登录验证就可以访问的地址
                .antMatchers("/index", "/Login.html", "/login", "/js/**").permitAll()
                .antMatchers("/access/user").hasRole("USER")//设置什么请求需要什么角色才可以访问
                .antMatchers("/access/read").hasRole("READ")
                .antMatchers("/access/admin").hasRole("ADMIN")
                .anyRequest().authenticated()//设置其他必须要验证
                .and()
                .formLogin()
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                //指定自定义登录页面
                .loginPage("/Login.html")
                //指定表单form中登录访问的url地址
                .loginProcessingUrl("/login")
                .and()
                //关于跨域访问的安全设置,先禁用
                .csrf().disable();
    }
}

  1. 自定义登录

    1. 传统form登录

      1. 创建页面
        1. action: /login 可以自定义
        2. method:post 这个是一定的
      2. 参数: username ,password 可以自定义
        1. 可以使用 http 对象.usernameParameter("myname")
        2. http 对象.passwordParameter("mypwd")进行更改
      3. 编写错误提示页面
      4. 设置自定义登录参数
        1. 设置访问的白名单,无需登录验证就可以访问的地址(设置首页不需要验证的时候,需要一个控制器来跳转,否则跳转不了)
        2. 指定登录页面,登录的 uri 地址
        3. 指定登录错误的提示页面
        4. 关闭跨域访问的安全设置
    2. ajax登录

      1. api 说明:
        1. AuthenticationSuccessHandler: 当 spring security 框架验证用户信息成功后执行的接口, 执行的是 onAuthenticationSuccess()方法
        2. AuthenticationFailureHandler: 当 spring security 框架验证用户信息失败后执行的接口, 接口中方法 onAuthenticationFailure()方法
      2. 实现步骤:
        1. 加入jquery.js文件在页面中发送ajax请求
        2. 创建 handler 实现两个不同接口(AuthenticationSuccessHandler,AuthenticationFailureHandler
        3. 导入jackson 依赖,使用jackson对json数据进行封装
        4. 创建作为结果的对象 Resul
        5. 配置 handler

 1.传统form登录

package com.example.user_role.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
public class configCustomSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationSuccessHandler successHandler;
    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //   super.configure(auth);
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    //设置首页不需要认证
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("555555555555555");
        http.authorizeHttpRequests()
                .antMatchers("/index", "//login_ajax.html", "/login", "/js/**").permitAll()//设置首页和自定义登陆页面不需要授权就可以登入
                .antMatchers("/access/user").hasRole("USER")//设置什么请求需要什么角色
                .antMatchers("/access/read").hasRole("READ")
                .antMatchers("/access/admin").hasRole("ADMIN")
                .anyRequest().authenticated()//设置其他必须要验证
                .and()
                .formLogin()
                .loginPage("/login_ajax.html")//指定自定义登录页面
                .loginProcessingUrl("/login")//指定表单form中登录访问的url地址
                .failureUrl("/error.html")//指定登录错误的提示页面
                .and()
                .csrf().disable();//关于跨域访问的安全设置,先禁用
    }
}

2.ajax登录

①加入jquery.js文件在页面中发送ajax请求

<script type="text/javascript">
        $(function () {
            $("#btnlogin").click(function () {
                alert(6666666);
                var name = $("#username").val();
                var password = $("#password").val();
                $.ajax({
                    url: "/login",
                    type: "POST",
                    data: {
                        "username": name,
                        "password": password
                    },
                    dataType: "json",
                    success: function (resp) {
                        alert("代码:"+resp.code+"提示:"+resp.msg);
                    }
                })
            })
        })
    </script>

②创建 handler 实现两个不同接口(AuthenticationSuccessHandler,AuthenticationFailureHandler)并导入jackson 依赖,使用jackson对json数据进行封装

AuthenticationFailureHandler:

package com.example.user_role_ajax.common;

import com.example.user_role_ajax.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
import java.io.OutputStream;
import java.io.PrintWriter;


@Component
public class MyFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        //登录的用户信息验证失败后执行的方法
        response.setContentType("text/json;charset=utf-8");
        Result result = new Result();
        result.setCode(1);
        result.setError(1000);
        result.setMsg("登入失败");

        OutputStream out = response.getOutputStream();
        ObjectMapper om = new ObjectMapper();
        om.writeValue(out,result);
        out.flush();
        out.close();
    }
}

 AuthenticationSuccessHandler:

package com.example.user_role_ajax.common;

import com.example.user_role_ajax.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
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;
import java.io.OutputStream;
import java.io.PrintWriter;

@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {
    /*参数
    request:请求对象
    response:应答对象
    authentication:spring security框架验证用户信息成功后的封住类
    * */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //登录的用户信息验证成功后执行的方法
        response.setContentType("text/json;charset=utf-8");

        Result result = new Result();
        result.setCode(0);
        result.setError(1000);
        result.setMsg("登入成功");

        OutputStream out = response.getOutputStream();
        ObjectMapper om = new ObjectMapper();//使用jackson
        om.writeValue(out,result);
        out.flush();
        out.close();


    }
}

创建作为结果的对象 Resul

package com.example.user_role_ajax.result;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
    //0:成功;1:失败
    private int code;
    //错误码
    private int error;
    //消息文本
    private String msg;

}

配置 handler

package com.example.user_role_ajax.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
public class configCustomSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationSuccessHandler successHandler;
    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //   super.configure(auth);
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    //设置首页不需要认证
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                //设置访问的白名单,无需登录验证就可以访问的地址
                .antMatchers("/index", "/Login.html", "/login", "/js/**").permitAll()
                .antMatchers("/access/user").hasRole("USER")//设置什么请求需要什么角色才可以访问
                .antMatchers("/access/read").hasRole("READ")
                .antMatchers("/access/admin").hasRole("ADMIN")
                .anyRequest().authenticated()//设置其他必须要验证
                .and()
                .formLogin()
                .successHandler(successHandler)//配置handler
                .failureHandler(failureHandler)//配置handler
                //指定自定义登录页面
                .loginPage("/Login.html")
                //指定表单form中登录访问的url地址
                .loginProcessingUrl("/login")
                .and()
                //关于跨域访问的安全设置,先禁用
                .csrf().disable();
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值