Springboot开启SpringSecurity

一、创建springboot项目

版本:2.3.1.RELEASE

添加security 依赖

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-security</artifactId>

        </dependency>

二、启动项目

默认开启Spring Security 安全认证

 

默认的用户名为user ,密码随机生成

访问 http://localhost:8080/ 未登录会跳到 默认的

http://localhost:8080/login 登陆接口

 

三、配置认证方式

WebSecurityConfigurerAdapter是由Spring Security提供的Web应用安全配置的适配器

import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

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

@Configuration

public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

@Override

protected void configure(HttpSecurity http) throws Exception {

//http.formLogin() //表单认证方式

http.httpBasic() // HTTP Basic方式

.and()

.authorizeRequests() // 授权配置

.anyRequest() // 所有请求

.authenticated();// 都需要认证;

}

}

http.formLogin() //表单认证方式 默认的认证方式

表单登陆

 

http.httpBasic() // HTTP Basic方式

窗口登陆

 

四、基本原理

过滤器和拦截器

说明

UsernamePasswordAuthenticationFilter

用于处理基于表单方式的登录认证

BasicAuthenticationFilter

处理基于HTTP Basic方式的登录验证

FilterSecurityInterceptor

用于判断当前请求身份认证是否成功,是否有相应的权限

ExceptionTranslationFilter

用于处理了FilterSecurityInterceptor抛出的异常并进行处理

原文地址:https://www.cnblogs.com/kali5k/p/13227238.html