繁体   English   中英

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

[英]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定义了两种授权类型

  1. 客户证书授予
  2. 资源所有者密码凭证授予

在这两种情况下,您都将跳过登录屏幕并调用令牌端点以获取访问令牌。 请阅读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(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

下图提到成功响应。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM