带有JWT的Spring Security OAuth2重定向到登录页面

时间:2019-09-11 05:33:31

标签: java spring spring-security oauth-2.0 jwt

我用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。授权和请求正文在图片下方定义。

enter image description here

enter image description here

执行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>

非常感谢您提供帮助或解决此问题的方法。

2 个答案:

答案 0 :(得分:0)

OP真正想要的是获取访问令牌,就像从API获取访问令牌一样。

为此,OAuth 2.0定义了两种授权类型

  1. Client Credentials Grant
  2. Resource Owner Password Credentials Grant

在两种情况下,您都将跳过登录屏幕并调用令牌端点以获取访问令牌。请阅读RFC(上面的链接)以了解何时应在何处采用这些授权类型。

我不是Spring专家,因此在这里我链接到网上找到的教程,该教程解释了Spring的两种资助。

答案 1 :(得分:0)

我添加了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类中,删除公共无效的configure(ClientDetailsS​​erviceConfigurer客户端)方法并添加以下代码。

@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

下图中提到的成功响应。

enter image description here

相关问题