Spring-security-oauth2 comments

Source: Internet
Author: User
Tags oauth

The annotations supported by SPRING-SECURITY-OAUTH2 are:

1.enableoauth2client

For Web application environment code that uses spring security and wants to obtain authorization from the Oauth2 authentication server, it has a OAUTH2 client configuration enabled. To make better use of this feature, you need to add a servlet filter in the client application Delegatingfilterproxy (proxy a named Oauth2clientcontextfilter). When the filter is configured to the client app, you can use another bean provided by the annotation @accesstokenrequest to create a oauth2requesttemplate. Example:

  @Configuration  @EnableOAuth2Client  public class  remoteresourceconfiguration {     @Bean   public  oauth2restoperations resttemplate ( Oauth2clientcontext oauth2clientcontext) {          returnnew  oauth2resttemplate ( Remote (), oauth2clientcontext);      }    }

The client app uses client credential authorization and does not require accesstokenrequest or intra-domain restoperation (the state is global to the app). However, filter is used to trigger oauth2restoperation when needed to obtain tokens. A password-licensed app needs to set the authentication properties for Oauth2protectedresoucedetail before the restoperation action, which means that resouce detail itself needs a session (assuming there are multiple users in the system).

@Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documented @import (oauth2clientconfiguration. class ) public @Interface  enableoauth2client {}

Implement Oauth2clientconfiguration

@Configuration Public classoauth2clientconfiguration {@Bean PublicOauth2clientcontextfilter Oauth2clientcontextfilter () {oauth2clientcontextfilter filter=NewOauth2clientcontextfilter (); returnfilter; } @Bean @Scope (value= "Request", Proxymode =scopedproxymode.interfaces)protectedAccesstokenrequest accesstokenrequest (@Value ("#{request.parametermap}") Map<string, string[]> parameters, @Value ("#{request.getattribute (' Currenturi ')}") (String Currenturi) {defaultaccesstokenrequest request=Newdefaultaccesstokenrequest (parameters);        Request.setcurrenturi (Currenturi); returnrequest; } @Configurationprotected Static classoauth2clientcontextconfiguration {@Resource @Qualifier ("Accesstokenrequest")        Privateaccesstokenrequest accesstokenrequest; @Bean @Scope (Value= "Session", Proxymode =scopedproxymode.interfaces) PublicOauth2clientcontext Oauth2clientcontext () {return NewDefaultoauth2clientcontext (accesstokenrequest); }            }}

2. Enableauthorizationserver

Tool method for opening an authorization server (such as Authorizationendpoint) and a tokenendpoint in the current application context (must be a dispatcherservlet context). Several properties of the server can be customized by a bean that customizes the authorizationserverconfigurer type (such as Authorizationserverconfigureradapter extension). By using the featured enablewebsecurity of spring security, the user is responsible for securing the authorization Endpoint (/oauth/authorize), but token Endpoint (/oauth/token) The client credentials for HTTP basic are automatically used to ensure security. A clientdetailservice is provided through one or more authorizationserverconfigurer to register the client (must).

@Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documented @import ({ Authorizationserverendpointsconfiguration. class, Authorizationserversecurityconfiguration. class }) public @Interface  enableauthorizationserver {}

2.1 Authorizationserverendpointsconfiguration

    PrivateAuthorizationserverendpointsconfigurer endpoints =NewAuthorizationserverendpointsconfigurer (); @AutowiredPrivateClientdetailsservice Clientdetailsservice; @AutowiredPrivateList<authorizationserverconfigurer> configurers =collections.emptylist (); @PostConstruct Public voidinit () { for(Authorizationserverconfigurer configurer:configurers) {Try{configurer.configure (endpoints); } Catch(Exception e) {Throw NewIllegalStateException ("Cannot Configure Enpdoints", E);    }} endpoints.setclientdetailsservice (Clientdetailsservice); }

@Componentprotected Static classTokenkeyendpointregistrarImplementsBeandefinitionregistrypostprocessor {PrivateBeandefinitionregistry Registry; @Override Public voidPostprocessbeanfactory (Configurablelistablebeanfactory beanfactory)throwsbeansexception {string[] names=beanfactoryutils.beannamesfortypeincludingancestors (Beanfactory, Jwtaccesstokenconverter.class,false,false); if(Names.length > 0) {Beandefinitionbuilder builder= Beandefinitionbuilder.rootbeandefinition (tokenkeyendpoint.class); Builder.addconstructorargreference (names[0]); Registry.registerbeandefinition (tokenkeyendpoint.class. GetName (), builder.getbeandefinition ()); }} @Override Public voidPostprocessbeandefinitionregistry (Beandefinitionregistry Registry)throwsbeansexception { This. Registry =Registry; }    }

2.2 Authorizationserversecurityconfiguration

@Configuration @order (0) @Import ({clientdetailsserviceconfiguration.class, Authorizationserverendpointsconfiguration.class }) Public classAuthorizationserversecurityconfigurationextendsWebsecurityconfigureradapter {@AutowiredPrivateList<authorizationserverconfigurer> configurers =collections.emptylist (); @AutowiredPrivateClientdetailsservice Clientdetailsservice; @AutowiredPrivateauthorizationserverendpointsconfiguration Endpoints; @Autowired Public voidConfigure (Clientdetailsserviceconfigurer clientdetails)throwsException { for(Authorizationserverconfigurer configurer:configurers) {configurer.configure (clientdetails); }} @Overrideprotected voidConfigure (Authenticationmanagerbuilder auth)throwsException {//over-riding to make sure This.disablelocalconfigureauthenticationbldr = False//This would ensure that if this Configurer builds the AuthenticationManager it would not attempt//to find another ' Global ' AuthenticationManager in the ApplicationContext (if available),//and set that as the parent of this ' Local ' AuthenticationManager. //This AuthenticationManager should is wired up with an Authenticationprovider//composed of the Clientdetailsservice (wired in this configuration) for authenticating ' clients ' only.} @Overrideprotected voidConfigure (Httpsecurity http)throwsException {authorizationserversecurityconfigurer Configurer=NewAuthorizationserversecurityconfigurer (); Frameworkendpointhandlermapping handlermapping=endpoints.oauth2endpointhandlermapping (); Http.setsharedobject (frameworkendpointhandlermapping.class, handlermapping);        Configure (Configurer);        Http.apply (Configurer); String Tokenendpointpath= Handlermapping.getservletpath ("/oauth/token"); String Tokenkeypath= Handlermapping.getservletpath ("/oauth/token_key"); String Checktokenpath= Handlermapping.getservletpath ("/oauth/check_token"); if(!endpoints.getendpointsconfigurer (). Isuserdetailsserviceoverride ()) {Userdetailsservice Userdetailsservice= Http.getsharedobject (Userdetailsservice.class);        Endpoints.getendpointsconfigurer (). Userdetailsservice (Userdetailsservice); }        //@formatter: Offhttp. authorizerequests (). Antmatchers (Tokenendpointpath). fullyauthenticated () . Antmatchers (Tokenkeypath). Access (Configurer.gettokenkeyaccess ()). Antmatchers (Checktokenpath). ac Cess (Configurer.getchecktokenaccess ()). Requestmatchers (). Antmatchers (Tokenendpoi Ntpath, Tokenkeypath, Checktokenpath). and (). Sessionmanagement (). Sessioncreationpolicy (Sessioncreationp Olicy.        Never); //@formatter: onHttp.setsharedobject (Clientdetailsservice.class, Clientdetailsservice); }    protected voidConfigure (Authorizationserversecurityconfigurer oauthserver)throwsException { for(Authorizationserverconfigurer configurer:configurers) {configurer.configure (oauthserver); }    }}

Spring-security-oauth2 comments

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.