1. 程式人生 > >spring Security4 和 oauth2整合 註解+xml混合使用(基礎執行篇)

spring Security4 和 oauth2整合 註解+xml混合使用(基礎執行篇)

Spring Security4 和 oauth2整合

最近專案中需要用到oauth2,到網上找了好多資料,全是亂七八糟的,東拼西湊,終於跑出來了一版,xml的方式太亂了,跑不了,還是用註解方式,並把一些關鍵配置提到xml中。

git地址:https://gitee.com/xiaoyaofeiyang/OauthUmp

spring Security4 和 oauth2整合 註解+xml混合使用(基礎執行篇)
spring Security4 和 oauth2整合 註解+xml混合使用(進階篇)
spring Security4 和 oauth2整合 註解+xml混合使用(授權碼篇)


spring Security4 和 oauth2整合 註解+xml混合使用(注意事項篇)
spring Security4 和 oauth2整合 註解+xml混合使用(替換6位的授權碼)
spring Security4 和 oauth2整合 註解+xml混合使用(替換使用者名稱密碼認證)
spring Security4 和 oauth2整合 註解+xml混合使用(驗證碼等額外資料驗證)

網上已有的註解版方案(執行有問題,後面修正)

連結:http://www.yiibai.com/spring-security/secure-spring-rest-api-using-oauth2.html


這個連結沒說是springmvc或者springboot使用,反正我是用springmvc使用了,可以用,我這裡搬過來,同時寫上自己的程式碼。後面會修改。

pom.xml

<properties>
        <spring.version>4.0.5.RELEASE</spring.version>
        <jsonlib.version>2.4</jsonlib.version>
        <spring.security.version>4.0.1.RELEASE</spring.security.version
>
</properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.1.0.RELEASE</version> </dependency> <!-- logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- end of logging --> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <!-- Json --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> <version>1.8.1</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-lgpl</artifactId> <version>1.8.1</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>${jsonlib.version}</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.3.3</version> </dependency> <!-- end of Json --> <!-- xstream --> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.10</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.20</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.2</version> </dependency> <!-- ehcache 相關依賴 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.2</version> </dependency> </dependencies>

ResourceServer

package com.yiibai.springmvc.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "my_rest_api";

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

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.
        anonymous().disable()
        .requestMatchers().antMatchers("/user/**")
        .and().authorizeRequests()
        .antMatchers("/user/**").access("hasRole('ADMIN')")
        .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

AuthorizationServer

package com.yiibai.springmvc.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private static String REALM="MY_OAUTH_REALM";

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

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

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

        clients.inMemory()
            .withClient("my-trusted-client")
            .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("read", "write", "trust")
            .secret("secret")
            .accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
            refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
    }

    @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(REALM+"/client");
    }

}

OAuth2SecurityConfiguration

package com.yiibai.springmvc.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
        .withUser("bill").password("abc123").roles("ADMIN").and()
        .withUser("bob").password("abc123").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers("/oauth/token").permitAll();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


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

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

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

}

MethodSecurityConfig

package com.yiibai.springmvc.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Autowired
    private OAuth2SecurityConfiguration securityConfig;

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }
}

最後

這樣就copy完了,不過springmvc不能用,需要在web.xml加上filter

  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

這樣就可以跑起來了,按照http://www.yiibai.com/spring-security/secure-spring-rest-api-using-oauth2.html提供的方法跑,不過你會發現,總是提示token錯誤。原因是tokenstore不一致。這樣就不要用@Bean註解了,寫在xml裡,用@AutoWired就行。

xml配置tokenstore

    <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore">
    </bean>

配置完成後,就可以將OAuth2SecurityConfiguration檔案中的tokenstore注掉。

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

然後在檔案AuthorizationServerConfiguration和ResourceServerConfiguration中的TokenStore @Autowired一下。

@Autowired
    private TokenStore tokenStore;

將clientdetails提到xml中

clientdetails寫在程式碼裡,不方便替換,可以寫到配置檔案中。

<bean id="myClientDetailsService"
        class="org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService">
        <property name="clientDetailsStore">
            <map>
                <entry key="MwonYjDKBuPtLLlK" value-ref="clientDetails" />
                <entry key="VJUpAlhdWPbvkpPy" value-ref="clientDetails1" />
            </map>
        </property>

    </bean>

    <bean id="clientDetails"
        class="org.springframework.security.oauth2.provider.client.BaseClientDetails">
        <property name="clientId" value="MwonYjDKBuPtLLlK" />
        <property name="clientSecret" value="secret" />
        <property name="accessTokenValiditySeconds" value="120" />
        <property name="refreshTokenValiditySeconds" value="600" />
        <property name="scope">
            <set>
                <value>read</value>
                <value>write</value>
                <value>trust</value>
            </set>
        </property>
        <property name="authorizedGrantTypes">
            <set>
                <value>password</value>
                <value>authorization_code</value>
                <value>refresh_token</value>
                <value>implicit</value>
            </set>
        </property>
        <property name="authorities">
            <list>
                <bean
                    class="org.springframework.security.core.authority.SimpleGrantedAuthority">
                    <constructor-arg type="java.lang.String" value="ROLE_CLIENT"></constructor-arg>
                </bean>
                <bean
                    class="org.springframework.security.core.authority.SimpleGrantedAuthority">
                    <constructor-arg type="java.lang.String" value="ROLE_TRUSTED_CLIENT"></constructor-arg>
                </bean>
            </list>
        </property>
    </bean>
    <bean id="clientDetails1"
        class="org.springframework.security.oauth2.provider.client.BaseClientDetails">
        <property name="clientId" value="VJUpAlhdWPbvkpPy" />
        <property name="clientSecret" value="secret" />
        <property name="accessTokenValiditySeconds" value="120" />
        <property name="refreshTokenValiditySeconds" value="600" />
        <property name="scope">
            <set>
                <value>read</value>
                <value>write</value>
                <value>trust</value>
            </set>
        </property>
        <property name="authorizedGrantTypes">
            <set>
                <value>password</value>
                <value>authorization_code
            
           

相關推薦

spring Security4 oauth2整合 註解+xml混合使用驗證碼等額外資料驗證

spring Security4 和 oauth2整合(驗證碼等額外資料驗證) 上一篇寫的自定義使用者名稱密碼驗證,這裡寫驗證碼的驗證,或者其他資訊的驗證。 git地址:https://gitee.com/xiaoyaofeiyang/OauthUmp spring Securi

spring Security4 oauth2整合 註解+xml混合使用替換使用者名稱密碼認證

spring Security4 和 oauth2整合 (替換使用者名稱密碼認證) 之前已經寫了註解和xml配合搭建基本認證、頁面認證、授權碼認證、替換6位授權碼方法等,這次在前面的基礎上介紹如何替換使用者名稱密碼認證,下一篇介紹如何增加驗證碼等額外引數驗證方法。 程式碼比較多,這次只

spring Security4 oauth2整合 註解+xml混合使用替換6位的授權碼

spring Security4 和 oauth2整合替換6位的授權碼 git地址:https://gitee.com/xiaoyaofeiyang/OauthUmp spring Security4 和 oauth2整合 註解+xml混合使用(基礎執行篇) spring Secu

spring Security4 oauth2整合 註解+xml混合使用注意事項

Spring Security4 和 oauth2整合注意事項 git地址:https://gitee.com/xiaoyaofeiyang/OauthUmp spring Security4 和 oauth2整合 註解+xml混合使用(基礎執行篇) spring Security

spring Security4 oauth2整合 註解+xml混合使用授權碼

Spring Security4 和 oauth2整合授權碼模式 上兩篇介紹了環境配置和使用者密碼模式,下面介紹授權碼模式。 git地址:https://gitee.com/xiaoyaofeiyang/OauthUmp spring Security4 和 oauth2整合 註

spring Security4 oauth2整合 註解+xml混合使用進階

Spring Security4 和 oauth2整合使用者密碼授權模式 上篇已經可以正常運行了,不過拿來測試還不夠,下面介紹如何測試oauth2的使用者密碼模式,授權碼模式下一篇說。 不想看這些亂七八糟的,可以直接把程式碼拉下來。 git地址:https://gitee.com/x

spring Security4 oauth2整合 註解+xml混合使用基礎執行

Spring Security4 和 oauth2整合 最近專案中需要用到oauth2,到網上找了好多資料,全是亂七八糟的,東拼西湊,終於跑出來了一版,xml的方式太亂了,跑不了,還是用註解方式,並把一些關鍵配置提到xml中。 git地址:https://gitee.com/xiao

Spring boot實戰專案整合阿里雲RocketMQ 非開源版訊息佇列實現傳送普通訊息,延時訊息 --附程式碼

一.為什麼選擇RocketMQ訊息佇列? 首先RocketMQ是阿里巴巴自研出來的,也已開源。其效能和穩定性從雙11就能看出來,借用阿里的一句官方介紹:歷年雙 11 購物狂歡節零點千萬級 TPS、萬億級資料洪峰,創造了全球最大的業務訊息併發以及流轉紀錄(日誌類訊息除外);  在始終保證高效能前提下

面試題:字串出現次數最多的字母次數基礎思路

今天中午公司要求的小功能寫完之後,想了想之前的一道面試題。 題目: 給一個字串,找到出現次數最多的字母和次數(手寫程式碼) 當時想到了用map,但是寫了一半感覺到自己對map還是不熟練,手寫寫不出來,於是就換了個思路。 原理: 通過字串分割函式分割字串,判斷分割後的長度來比較字母的次

使用Spring SecurityOAuth2實現RESTful服務安全認證

schema repo gradle nbsp tps protect 一個 ndb lac 這篇教程是展示如何設置一個OAuth2服務來保護REST資源. 源代碼下載github. (https://github.com/iainporter/oauth2-provide

Spring MvcSpringBoot整合Swagger2

各位同學大家好,最近專案趕進度,沒有鑽研技術的時間,但碰巧今天需要在Spring專案上進行SpringMvc和Swagger的整合,而第一次使用Swagger是在SpringBoot專案上,因此踩了不少的坑,於是想和大家分享一下 :關於Swagger在SpringBoot或者和SpringMvc的整

Spring BootDubbo整合

  程式碼demo http://git.oschina.net/zhangxh20/spring-boot-dubbo 專案共分成4個模組 dubbo-api dubbo-dao dubbo-service dubbo-web dubbo-

Spring Boot學習筆記Spring Boot activeMQ整合

Spring Boot學習筆記使用步驟: Spring Boot:並不是不對 Spring 功能上的增強,而是提供了一種快速使用 Spring 的方式。 使用步驟: 1、起步依賴:pom.xml中配置起步依賴,會自動匯入spring相關的許多jar包 <

輕輕鬆鬆學習SpringBoot2:第二十五Spring BootMongodb整合完整版

今天主要講的是Spring Boot和Mongodb整合我們先來回顧一下前面章節的相關內容前面我們講了SpringBoot和mysql整合,並且講了操作資料庫的幾種方式自動生成表資料庫操作操作篇回到正題,mongodb的安裝在這就不累述了,win版本的去官網下載,然後一直下一

Spring系列之Spring框架SpringAOP整合過程分析(十二)

轉載請註明出處:https://blog.csdn.net/zknxx/article/details/80808447 在這篇文章中我們接著上一篇的文章說。在上一篇文章中我們提到了getAdvicesAndAdvisorsForBean這個方法,這個方法的內

Spring系列之Spring框架SpringAOP整合過程分析(十)

轉載請註明出處:https://blog.csdn.net/zknxx/article/details/80724180 在開始這個系列之前大家先想一下我們是怎麼在專案中使用SpringAOP的(這裡的分析都是基於AspectJ註解的)。我們需要在我們的Spr

spring bootmybatis整合

maven的依賴配置 <!-- spring boot 版本號 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>

spring junit4junit5整合測試,3步走

1、導包spring-test-5.0.7.RELEASE.jar 2、使用註解改變執行main函式 3、指定spring的配置檔案 junit4示範程式碼 //改變junit的執行Runner

spring-orm Hibernate整合

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" re

spring-boot redis 整合的一個小例子

轉自:http://blog.csdn.net/a67474506/article/details/52595053 在網上看到好多的spring-boot和redis整合的,弄到本地一直報Error resolving template "get", template m