[英]Spring Security OAuth2 with JWT redirect to login page
我使用OAuth2和JWT創建了Spring Security應用程序。 當它運行時,我得到一個登錄頁面。 下面我提到了pom.xml
文件。
<?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.0.0.RELEASE</version>
</parent>
<groupId>com.java.oauth</groupId>
<artifactId>AuthorizationWithOauth2nJWT</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>AuthorizationWithOauth2nJWT</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.0.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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>
下面提到了AuthorizationServerConfig.java
文件。
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private String clientId = "client-id";
private String clientSecret = "my-secret";
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager getauthenticationManager;
@Bean
public JwtAccessTokenConverter tokenEnhancer() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(tokenEnhancer());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(getauthenticationManager).tokenStore(tokenStore())
.accessTokenConverter(tokenEnhancer());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(clientId)
.secret(clientSecret)
.scopes("read", "write", "trust")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.accessTokenValiditySeconds(20000)
.refreshTokenValiditySeconds(20000);
}
}
這是ResourceServerConfig.java文件。
@Configuration
@EnableResourceServer
@Order(100)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.requestMatchers().antMatchers("/oauth/**")
.and()
.authorizeRequests()
.antMatchers("/oauth/**").authenticated();
}
}
這是SecurityConfig.java文件。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/getuser").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.csrf().disable();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
下面我提到了application.yml文件
server:
port: 8081
spring:
security:
user:
name: test
password: test
security:
oauth2:
resource:
filter-order: 3
我使用郵遞員執行API。 授權和請求主體在下面的圖像中定義。
執行完API后,我得到以下200狀態代碼的響應。
<html>
<head>
<title>Login Page</title>
</head>
<body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3>
<form name='f' action='/login' method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password'/></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit" value="Login"/></td>
</tr>
</table>
</form>
</body>
</html>
對於解決此問題的任何幫助或解決方法,我們深表感謝。
OP真正想要的是在這里獲取訪問令牌,就像從API中獲取訪問令牌一樣。
為此,OAuth 2.0定義了兩種授權類型
在這兩種情況下,您都將跳過登錄屏幕並調用令牌端點以獲取訪問令牌。 請閱讀RFC(以上鏈接)以了解何時何地應采用這些授予類型。
我不是Spring專家,因此在這里我鏈接到網上找到的教程,該教程解釋了Spring的這兩項資助。
我添加了UserConfig.java類,並添加了以下代碼。
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("test")
.password(passwordEncoder.encode("test123"))
.roles("USER","ADMIN","MANAGER")
.authorities("CAN_READ","CAN_WRITE","CAN_DELETE");
}
在AuthorizationServerConfig.java類中,刪除公共void configure(ClientDetailsServiceConfigurer客戶端)方法,然后添加以下代碼。
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("password"))
.scopes("READ", "WRITE")
.authorizedGrantTypes("password", "refresh_token", "id_token");
}
我刪除了application.yml文件中的以下配置
spring:
security:
user:
name: test
password: test
下圖提到成功響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.