29.Spring Security Oauth2授权模式
1.新建一个springboot项目叫springsecurityoauth2-demo
2.修改pom文件及添加依赖
<?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.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.night</groupId>
<artifactId>springsecurityoauth2-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springsecurityoauth2-demo</name>
<description>springsecurityoauth2-demo</description>
<properties>
<java.version>1.8</java.version>
<!--声明 spring cloud 的版本号:格林威治-->
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencies>
<!--Oauth2依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<!--security依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!--引入spring cloud依赖-->
<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>
SpringSecurity在引入依赖之后会有一个默认的用户还有一个默认的密码,这个密码是项目启动的时候控制台打印输出的,那我们需要去定义一个自定义的登录逻辑,然后修改默认的用户名和密码。
3.创建service业务逻辑层的UserService类
//业务逻辑层注解
@Service
//实现UserDetailsService
public class UserService implements UserDetailsService {
//注入PasswordEncoder
@Autowired
private PasswordEncoder passwordEncoder;
//实现方法
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//修改默认密码
String password = passwordEncoder.encode("123456");
return new User("admin", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
4.创建springSecurity对应的一个配置类config》SecurityConfig.java
/**
* @author etern
* @title: SecurityConfig
* @projectName springsecurityoauth2-demo
* @description: TODO
* @date 2022/2/15 22:05
*/
//配置类注解
@Configuration
//启动websecurity注解
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//密码容器
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
//拦截放行配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/oauth/**", "/login/**", "logout/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.permitAll();
}
}
5.创建一个自己定义的类包封装起来SpringSecurity的User
pojo》User.java
/**
* @author etern
* @title: User
* @projectName springsecurityoauth2-demo
* @description: TODO 自定义的User方法
* @date 2022/2/17 15:31
*/
public class User implements UserDetails {
//账号
private String username;
//密码
private String password;
//权限
private List<GrantedAuthority> authorities;
//有参构造
public User(String username, String password, List<GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.authorities = authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
}
6.创建授权服务器配置
/**
* @author etern
* @title: AuthorizationServerConfig
* @projectName springsecurityoauth2-demo
* @description: TODO 授权服务器配置
* @date 2022/2/17 15:57
*/
//配置类注解
@Configuration
//启用授权服务器注解
@EnableAuthorizationServer
//继承AuthorizationServerConfigurerAdapter类
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
//注入自定义的密码配置
@Autowired
private PasswordEncoder passwordEncoder;
//重写configure中参数是clients
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
//配置client-id
.withClient("admin")
//配置client-secret
.secret(passwordEncoder.encode("112233"))
//配置访问token的有效时间(秒)
//.accessTokenValiditySeconds(3600)
//配置刷新token的有效时间(秒)
//.refreshTokenValiditySeconds(864000)
//配置redirect-uri,用于授权成功后跳转
.redirectUris("http://www.baidu.com")
//配置申请的权限范围
.scopes("all")
//配置grant-type,表示授权类型(授权码模式)
.authorizedGrantTypes("authorization_code");
}
}
7.创建资源服务器配置
/**
* @author etern
* @title: ResourceServerConfig
* @projectName springsecurityoauth2-demo
* @description: TODO 资源服务器配置
* @date 2022/2/17 19:44
*/
//配置类注解
@Configuration
//开启资源服务器配置注解
@EnableResourceServer
//继承ResourceServerConfigurerAdapter
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
//重写configure中参数是http,进行资源放行
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//所有的请求都必须被认证才能访问
.anyRequest()
.authenticated()
.and()
.requestMatchers()
//放行了相对应的一些资源
.antMatchers("/user/**");
}
}
8.创建控制层controller,新建UserController.java
/**
* @author etern
* @title: UserController
* @projectName springsecurityoauth2-demo
* @description: TODO
* @date 2022/2/17 19:56
*/
@RestController
@RequestMapping("/user")
public class UserController {
/**
* @return { java.lang.Object}
* @throws
* @Author etern
* @Description //TODO 获取当前用户
* @Date 20:04 2022/2/17
* @Param * @param authentication
**/
@RequestMapping("/getCurrentUser")
public Object getCurrentUser(Authentication authentication) {
return authentication.getPrincipal();
}
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 Eternal Night
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果