OAuth2+Spring Security简单实现用户登陆鉴权
一、引入主要依赖库
<!-- thymeleaf 模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<!-- Spring Security OAuth2 客户端支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
二、使用步骤
1.创建配置类
OAuth2Config.java:
package com.main.third.party.oauth2.config;
import com.main.third.party.oauth2.service.CustomUserDetailsService;
import com.main.third.party.oauth2.service.MyBatisClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService userDetailsService;
private static final String CLIENT_ID = "cjw";
private static final String SECRET_CHAR_SEQUENCE = "{noop}secret";
private static final String ALL = "all";
private static final String REFRESH_TOKEN = "refresh_token";
private static final String IMPLICIT_GRANT_TYPE = "implicit";
//重定向URI
private static final String REDIRECT_URI = "https://www.youkuaiyun.com";
//24小时过期时间
private static final int ACCESS_TOKEN_VALIDITY_SECONDS = 24 * 60 * 60 ;
//一个月过期时间
private static final int REFRESH_TOKEN_VALIDITY_SECONDS = 30 * 24 * 60 * 60 ;
// 密码模式授权模式
private static final String GRANT_TYPE_PASSWORD = "password";
//授权码模式
private static final String AUTHORIZATION_CODE = "authorization_code";
//简化授权模式
private static final String IMPLICIT = "implicit";
//客户端模式
private static final String CLIENT_CREDENTIALS = "client_credentials";
@Autowired
private MyBatisClientDetailsService clientDetailsService;
//手动内存存入客户端信息
// @Override
// public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// clients
// .inMemory()
// .withClient(CLIENT_ID)
// .secret(passwordEncoder.encode("secret"))
// .autoApprove(true)//自动允许
// .redirectUris(REDIRECT_URI) //重定向uri
// .scopes(ALL)
// .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
// .refreshTokenValiditySeconds(REFRESH_TOKEN_VALIDITY_SECONDS)
// .authorizedGrantTypes(AUTHORIZATION_CODE,REFRESH_TOKEN,IMPLICIT_GRANT_TYPE);
// }
//从数据库获取客户端信息
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)//设置认证管理器
.tokenStore(memoryTokenStore())//配置内存令牌存储
.userDetailsService(userDetailsService);//绑定用户详情服务
}
/**
* 认证服务器的安全配置
*
* @param security
* @throws Exception
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
// 开启/oauth/check_token验证端口认证权限访问,checkTokenAccess("isAuthenticated()")设置授权访问
.checkTokenAccess("permitAll()")
//允许表单认证
.allowFormAuthenticationForClients();
}
@Bean
public TokenStore memoryTokenStore() {
return new InMemoryTokenStore();
}
}
CustomUserDetailsService.java(授权页用户登录服务):
package com.main.third.party.oauth2.service;
import com.main.third.party.oauth2.domain.entity.User;
import com.main.third.party.oauth2.domain.mapper.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
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;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
//校验用户登录信息
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);//这里可以自定义你的用户信息
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
return new org.springframework.security.core.userdetails.User(
user.getPhone(),
user.getPassword(),
AuthorityUtils.createAuthorityList("ROLE_ADMIN")
);
}
}
MyBatisClientDetailsService.java(这个是获取client信息,可以写个注册接口或者直接在数据库生成):
package com.main.third.party.oauth2.service;
import com.main.third.party.oauth2.domain.entity.ClientDetailsPO;
import com.main.third.party.oauth2.domain.entity.ClientDetailsEntity;
import com.main.third.party.oauth2.domain.mapper.ClientDetailsMapper;
import com.main.third.party.oauth2.utils.Sha256PasswordEncoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class MyBatisClientDetailsService implements ClientDetailsService {
private static final String DELIMITER = ","; // 定义分隔符
@Autowired
private ClientDetailsMapper clientDetailsMapper;
//查询客户端信息
@Override
public ClientDetailsPO loadClientByClientId(String clientId) throws ClientRegistrationException {
ClientDetailsEntity clientDetails = clientDetailsMapper.findByClientId(clientId);
if (clientDetails == null) {
throw new ClientRegistrationException("Client not found: " + clientId);
}
ClientDetailsPO clientDetailsEntity = new ClientDetailsPO();
BeanUtils.copyProperties(clientDetails, clientDetailsEntity);
//手动转换映射关系
clientDetailsEntity.setScope(convertToEntityAttribute(clientDetails.getScope()));
clientDetailsEntity.setAuthorizedGrantTypes(convertToEntityAttribute(clientDetails.getAuthorizedGrantTypes()));
clientDetailsEntity.setRegisteredRedirectUri(convertToEntityAttribute(clientDetails.getRegisteredRedirectUri()));
//加载默认权限
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
clientDetailsEntity.setAuthorities(authorities);
return clientDetailsEntity;
}
public Set<String> convertToEntityAttribute(String dbData) {
if (dbData == null || dbData.trim().isEmpty()) {
return Collections.emptySet();
}
return new HashSet<>(Arrays.asList(dbData.split(DELIMITER)));
}
}
ClientDetailsEntity.java 实体类:
package com.main.third.party.oauth2.domain.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.mzgd.mzaio.third.party.domain.BaseEntity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
@Data
@TableName("sys_client_detail")
public class ClientDetailsEntity extends BaseEntity implements Serializable {
private String clientName;
private String info;
@TableId(type = IdType.ASSIGN_ID )
private String clientId;
private String clientSecret;
private String scope;
private String authorizedGrantTypes;
private String registeredRedirectUri;//重定向uri
private Integer accessTokenValiditySeconds;//token过期时间
private Integer refreshTokenValiditySeconds;//refreshToken过期时间
private boolean isAutoApprove;
}
Oauth2ResourceServerConfiguration.java 资源授权器配置:
package com.main.third.party.oauth2.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
@Configuration
@EnableResourceServer
public class Oauth2ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
private static final String CHECK_TOKEN_URL = "http://localhost:8016/thirdParty/oauth/check_token";
// @Override
// public void configure(ResourceServerSecurityConfigurer resources) {
// RemoteTokenServices tokenService = new RemoteTokenServices();
// tokenService.setCheckTokenEndpointUrl(CHECK_TOKEN_URL);
// tokenService.setClientId("cms");
// tokenService.setClientSecret("secret");
// resources.tokenServices(tokenService);
// }
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()//禁用了csrf(跨站请求伪造)功能
.authorizeRequests()//限定签名成功的请求
// 需要认证后才能访问
.antMatchers("/user/**","/device/**","/product/**").authenticated()
// 免验证请求
.antMatchers("/oauth/**").permitAll();
}
}
PasswordEncoderConfig.java(client密钥登录免加密配置,不然填写的密钥会被Sha256PasswordEncoder加密):
package com.main.third.party.oauth2.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
SecurityConfig.java配置:
package com.main.third.party.oauth2.config;
import com.main.third.party.oauth2.service.CustomUserDetailsService;
import com.main.third.party.oauth2.utils.Sha256PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private Sha256PasswordEncoder passwordEncoder;//自定义的加密方式
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { //auth.inMemoryAuthentication()
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
public void configure(WebSecurity web) throws Exception {
//解决静态资源被拦截的问题
// web.ignoring().antMatchers("/asserts/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//拦截所有请求 通过httpBasic进行认证
// http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
http.csrf().disable();
http.requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**","/login.html")
.and()
.authorizeRequests()
.antMatchers("/oauth/**").authenticated()
.and()
.formLogin()
// 自定义登录页面
.loginPage("/login.html")
// 登录处理url
.loginProcessingUrl("/login")
.failureUrl("/login.html?error=true")
.and()
.httpBasic();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Sha256PasswordEncoder.java
package com.main.third.party.oauth2.utils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Component
public class Sha256PasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return encodePassword(rawPassword.toString());
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodePassword(rawPassword.toString()).equals(encodedPassword);
}
private String encodePassword(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(password.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256 algorithm not found", e);
}
}
}
login.html自定义授权登录页面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.login-container {
width: 100%;
max-width: 400px;
background-color: #ffffff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 8px;
padding: 30px;
text-align: center;
margin-bottom: 60px;
}
.title {
margin-bottom: 20px;
font-size: 24px;
color: #333333;
}
.form-group {
margin-bottom: 15px;
text-align: left;
}
.form-group label {
display: block;
margin-bottom: 5px;
color: #555555;
}
.form-group input {
width: 100%;
padding: 10px;
border: 1px solid #cccccc;
border-radius: 4px;
box-sizing: border-box;
}
.btn {
width: 100%;
padding: 10px;
background-color: #209bfa;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.btn:hover {
background-color: #1274e7;
}
</style>
</head>
<body>
<div class="login-container">
<div class="title">第三方授权平台</div>
<form class="form-signin" method="post" action="/thirdParty/login">//这里/thirdparty是我的应用上下文,没有就不加上,不然会404
<div class="form-group">
<label for="username">用户名</label>
<input type="text" id="username" name="username" placeholder="用户名" required autofocus>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" id="password" name="password" placeholder="密码" required>
</div>
<p style="color: #ff0000" th:if="${errorMessage}" th:text="${errorMessage}"></p>
<button class="btn" type="submit">登录</button>
</form>
</div>
</body>
</html>
这里还要写个Controller类配置登录错误信息并返回login.html页面:
@Controller
public class MyController {
@GetMapping("/login.html")
public String login(@RequestParam(value = "error", required = false) String error, Model model) {
if (error!=null&&error.equals("true")) {
model.addAttribute("errorMessage", "用户名或密码错误");
}
return "login";
}
}
SecurityConfiguration.java:
package com.main.third.party.oauth2.config;
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 SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").authenticated();
// 禁用CSRF
http.csrf().disable();
}
}
2.使用流程
1.客户端注册接口/oauth2/register,其实就是注册clientName、secretKey、redirectUri等信息,可以自定义
2.获取授权页面/oauth/authorize,如在浏览器打开http://localhost:8016/thirdParty/oauth/authorize?client_id=1895000429524160513&cliect_secret=ZY-A3LEcOfBfhBStRQPOQYm_pxrd4d8OyDCIO7mXji8&response_type=code
登录后在重定向页面获取到授权码code:
3.拿这个授权码去申请token,如http://localhost:8016/thirdParty/oauth/token?grant_type=authorization_code&client_id=1895000429524160513&client_secret=ZY-A3LEcOfBfhBStRQPOQYm_pxrd4d8OyDCIO7mXji8&code=2Yq2Fc&redirect_uri=https://www.youkuaiyun.com
4.刷新token接口:
5.检验token接口:
http://localhost:8016/thirdParty/oauth/check_token?token=cdece288-b569-4f23-a670-fb3995079f1e
总结
到这里简单的oauth2鉴权模块就已经完成了