当前位置: 首页 > 知识库问答 >
问题:

Spring http security在添加OAuth2后停止工作

李鹏
2023-03-14
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/home").authenticated()
    .and().formLogin()
    .and().httpBasic(); 
}

当我请求“http://localhost:8080/project/home”时,它会将我踢出“/login”。成功登录后,我现在可以查看“/home”

然后添加OAuth2,这与Sparklr2示例非常相同

@Configuration
public class OAuthServerConfig {
private static final String RESOURCE_ID = "cpe";



@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            // Since we want the protected resources to be accessible in the UI as well we need 
            // session creation to be allowed (it's disabled by default in 2.0.6)
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
        .and()
            .requestMatchers().antMatchers("/device/**", "/oauth/users/**", "/oauth/clients/**","/me")
        .and()
            .authorizeRequests()
                .antMatchers("/me").access("#oauth2.hasScope('read')")                  
                .antMatchers("/device").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")                                        
                //.antMatchers("/device/trusted/**").access("#oauth2.hasScope('trust')")
                .antMatchers("/device/user/**").access("#oauth2.hasScope('trust')")                 
                .antMatchers("/device/**").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")
                .antMatchers("/device/register").access("#oauth2.hasScope('write') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")
                .regexMatchers(HttpMethod.DELETE, "/oauth/users/([^/].*?)/tokens/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')")
                .regexMatchers(HttpMethod.GET, "/oauth/clients/([^/].*?)/users/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')")
                .regexMatchers(HttpMethod.GET, "/oauth/clients/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')");
        // @formatter:on
    }

}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;      
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    //needs to be change
    @Value("${tonr.redirect:http://localhost:8080/tonr2/sparklr/redirect}")
    private String tonrRedirectUri;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        //JdbcClientDetailsServiceBuilder           
        clients.jdbc(dataSource);           
    }

    @Bean
    public TokenStore tokenStore() {
        //return new InMemoryTokenStore();
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm("dragonfly/client");
    }

}

protected static class Stuff {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Bean
    public ApprovalStore approvalStore() throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

    @Bean
    @Lazy
    @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
    public DragonflyUserApprovalHandler userApprovalHandler() throws Exception {
        DragonflyUserApprovalHandler handler = new DragonflyUserApprovalHandler();
        handler.setApprovalStore(approvalStore());
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        handler.setUseApprovalStore(true);
        return handler;
    }
}

}

只有1个客户端详细信息

client.dataSource(dataSource)
    .withClient("my-trusted-client-with-secret")
     .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
     .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
     .scopes("read", "write", "trust")
     .secret("somesecret");

我在我的tomcat服务器上运行它,OAuth工作,我向/OAuth/token发出请求,它成功地将token返回给我。

我重新启动我的应用程序,然后请求/home,但没有登录,它会显示我的home视图和全部内容,没有登录,我无法理解。以下是我请求/home时的服务器日志

共有1个答案

方浩旷
2023-03-14

看起来您的项目设置和pom配置有问题

  1. 您添加了spring boot依赖项,但您没有使用spring boot。
  2. 您的项目打包为jar,但您有WEB-INF,并使用WebApplicationInitializer而不是spring Boot
  3. pom依赖项错误

我修改了几件事:

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

<groupId>com.umedia</groupId>
<artifactId>Dragonfly</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>Dragonfly</name>
<url>http://maven.apache.org</url>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.5</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.4.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4-1201-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.0.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
        <version>1.1.7</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.0</version>
            <configuration>
                <path>/</path>
            </configuration>
        </plugin>
    </plugins>
    <finalName>liveBLE</finalName>
</build>
</project>
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
 类似资料:
  • 我有一个使用javax.swing和java.awt的图形用户界面,请求焦点是保持文本字段的焦点,这样用户就可以从键盘开始。然后,我为每个整数0-9添加了按钮,以及一个清晰的字段按钮。然而,现在的焦点总是从按钮开始。 当我单击一个按钮时,焦点仍然返回到文本字段,或者如果我启动焦点,它仍然保留在文本字段中,我如何解决这个问题,并在每次窗口打开时将焦点放在文本字段上? 数字按钮示例 文本字段代码 检查

  • 我正在编写使用Spring Boot的小型web应用程序。一切都运行得很好,然后我添加了一些hibernate和Spring Security特性,现在我的不能工作了。现在我只得到一些关于像这样映射的日志: O.s.w.s.handler.SimpleURLHandlerMapping:将URL路径[/**/Favicon.ico]映射到类型为[class org.SpringFramework.

  • 我有一个按钮和一个HTML静态表。现在,我的工作是使用引导模式特性在弹出窗口上显示html表(假设这个情况类似于预览功能,用户点击预览按钮,他将看到他在表中输入的内容。)我目前正在工作的一个虚拟的桌子,我几乎完成了显示的桌子。 但是,问题来了。当点击关闭按钮后,弹出的窗口被关闭,如果我再次点击预览按钮,我会在弹出的窗口中看到两个表。请找到下面的代码片段(HTML表和JS脚本)。 帮助我如何避免关闭

  • 更新:我让原始节点离开集群,并重新启动它来测试它自己。它仍在抛出相同的错误。 更新:log/riak/solr.log的内容 2014-11-05 19:34:13,581[WARN]@coreadminhandler.java:495不允许使用现有名称创建核心2014-11-05 19:34:13,582[ERROR]@solrexception.java:109org.apache.solr.

  • 问题内容: 我正在尝试创建一个数据表,该数据表在忙时显示一个blockUI,并且我大多数时候都成功了。现在,当我单击两个commandButtons中的任何一个,通过单击标题对数据表进行排序,或在数据表中翻页时,它都会变灰并显示“正在加载…”。您可以在下面查看其代码。 问题是,在我使用了一个commandButtons(在受阻止的元素上运行ajax更新)之后,后续操作不会触发blockUI(直到刷

  • 问题内容: 有时,当我调用Selenium FindElements(By)时,它将引发异常,并且驱动程序停止工作。参数“ BY”可能是问题所在:当我使用其他BY搜索相同的元素时,它起作用了。 我也可以看到,即使我的元素存在,或者之前曾调用过带有相同参数的相同方法,也不会阻止该方法引发异常。 我的方法是: 一个BY值的示例并非始终有效(即使它存在于页面中): 例外: WebDriverExcept