其他
SpringBoot 跨系统单点登陆的实现 | CSDN 博文精选
作者 | 代码忘烦恼
责编 | 屠敏
出品 | CSDN 博客
降低访问第三方网站的风险(不存储用户密码,或在外部管理)
减少因不同的用户名和密码组合而带来的密码疲劳
减少为相同的身份重新输入密码所花费的时间
因减少与密码相关的调用IT服务台的次数而降低IT成本
密码模式(resource owner password credentials)
授权码模式(authorization code)
简化模式(implicit)
客户端模式(client credentials)
<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 http://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.1.6.RELEASE</version>
<relativePath/>
</parent>
<groupId>cn.com.scitc</groupId>
<artifactId>spring_sso_parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!-- 通用配置 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- spring oauth2 版本 -->
<oauth.version>2.3.6.RELEASE</oauth.version>
<!-- Spring Security OAuth2 AutoConfigure 版本 -->
<oauth-auto.version>2.1.6.RELEASE</oauth-auto.version>
</properties>
</project>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.scitc</groupId>
<artifactId>spring_sso_parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>cn.com.scitc</groupId>
<artifactId>oauth_server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>oauth_server</name>
<packaging>war</packaging>
<description>this is oauth2 server</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${oauth.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
<parent>
<groupId>cn.com.scitc</groupId>
<artifactId>spring_sso_parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login")
.antMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and().csrf().disable();
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//使用内存模拟数据库查询的用户
auth.inMemoryAuthentication() //内存认证
.withUser("admin")//admin 内存认证用户名
.password(passwordEncoder().encode("123456"))//被加密的123456密码
.roles("ADMIN");//ROLE_ADMIN的角色
}
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
http.requestMatchers()
.antMatchers("/login")
.antMatchers("/oauth/authorize")
.authorizeRequests()
.anyRequest().authenticated()
.formLogin().loginPage("/login").permitAll()
.and().csrf().disable();
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//使用内存模拟数据库查询的用户
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123456"))
.roles("ADMIN");
}
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public class OauthServerConfig extends AuthorizationServerConfigurerAdapter {
private PasswordEncoder passwordEncoder;
public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
public void configure(final ClientDetailsServiceConfigurer clients)
throws Exception {
clients.inMemory()
.withClient("handleCilentId")//客户端id
.secret(passwordEncoder.encode("secret"))//客户端密钥
.authorizedGrantTypes("authorization_code")//授权码模式
.scopes("user_info") //授权范围
.autoApprove(true)//开启自动授权
.redirectUris("http://localhost:8882/login") //认证成功重定向
.accessTokenValiditySeconds(10);//设置超时时间
}
}
clients.withClientDetails() :使用数据库认证
clients.jdbc(): 传入一个dataSource 这里可以使用自定义的dataSource
clients.inMemory():内存认证 相当于将认证信息 写死
public class LoginController {
public String loginPage() {
return "login";
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<h1>标准登陆</h1>
<form action="/auth/login" method="post">
username: <input type="text" name="username"/> <br/>
password: <input type="password" name="password"/> <br/>
<button type="submit">登陆</button>
</form>
</body>
</html>
public class UserInfoController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public ResponseEntity<Object> getUser(Principal principal) {
logger.info("principal:" + principal);
return new ResponseEntity<Object>(principal, HttpStatus.OK);
}
}
server:
port: 8880
servlet:
context-path: /auth
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.scitc</groupId>
<artifactId>spring_sso_parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>cn.com.scitc</groupId>
<artifactId>oauth_clinet1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>oauth_clinet1</name>
<description>this is client1</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>${oauth-auto.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2Sso
public class Oauth2ClientSeurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() //关闭csrf保护
.antMatcher("/**") //使用以任意开头的url
.authorizeRequests() // 配置路径拦截,表明路径访问所对应的权限,角色,认证信息
.antMatchers("/", "/login**") //控制不同的url接受不同权限的用户访问
.permitAll()// 允许所有人访问
.anyRequest()
.authenticated(); //除了以上请求都需要身份认证
}
}
public class InfoController {
public ResponseEntity<Object> userPage(Principal principal) {
//客户端认证成功后返回这个用户信息
return new ResponseEntity<Object>(principal, HttpStatus.OK);
}
public String indexPage() {
return "index";
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>请登录授权</h1>
<a href="/getUser">login</a>
</body>
</html>
auth-server: http://localhost:8880/auth
server:
port: 8881
servlet:
context-path: /
security:
basic:
enabled: false
oauth2:
client:
clientId: handleCilentId
clientSecret: secret
accessTokenUri: ${auth-server}/oauth/token
userAuthorizationUri: ${auth-server}/oauth/authorize
resource:
userInfoUri: ${auth-server}/user
spring:
thymeleaf:
cache: false
auth-server:是目标认证服务器
clientId:目标认证服务器设置的客户端id
clientSecret:目标认证服务器设置的密码
accessTokenUri:从目标认证服务器获取令牌token
userAuthorizationUri:从目标认证服务器请求授权默认url是/oauth/authorize
userInfoUri: 从目标认证服务器上将认证信息Principal通过形参绑定的方法通过URL的方式获取用户信息。
热 文 推 荐