1、引入spingsecurity依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
启动项目访问 http://localhost:8080/login 账号:user 密码:控制台系统生成的
2、配置自定义用户名密码
配置文件配置
# 应用服务 WEB 访问端口
server.port=8080
spring.security.user.name=admin
spring.security.user.password=123456
或者 方法中配置(优先级高)
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().
withUser("root"). // 用户名
password(this.passwordEncoder().encode("123")) 密码
.roles("admin"); //角色
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
3、获取当前登录用户信息
package com.example.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
@RestController
public class CurrentLoginUserInfoController {
/**
* 从当前请求对象中获取
*/
@GetMapping("/getLoginUserInfo")
public Principal getLoginUserInfo(Principal principle){
return principle;
}
/**
*从当前请求对象中获取
*/
@GetMapping("/getLoginUserInfo1")
public Authentication getLoginUserInfo1(Authentication authentication){
return authentication;
}
/**
* 从SecurityContextHolder获取
* @return
*/
@GetMapping("/getLoginUserInfo2")
public Authentication getLoginUserInfo(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication;
}
}
标签:使用,spingsecurity,springframework,说明,Authentication,org,import,security,annotatio From: https://www.cnblogs.com/chuanghongmeng/p/18008212