Getting Started with Spring oauth2.0 (actual combat)

Source: Internet
Author: User
Tags auth oauth static class

1. First Spring Security basic configuration

public class Servletinitializer extends Abstractannotationconfigdispatcherservletinitializer {

	...

	@Override public
	void Onstartup (ServletContext servletcontext) throws Servletexception {
		Super.onstartup ( ServletContext);
		/** urlrewritefilter **/
		*
		 * servletcontext.addfilter ("Urlrewritefilter",
		 * urlrewritefilter.class). Addmappingforurlpatterns (null, FALSE, "/*");
		 * *
		delegatingfilterproxy filter = new Delegatingfilterproxy ("Springsecurityfilterchain");
		Filter.setcontextattribute ("Org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
		Servletcontext.addfilter ("Springsecurityfilterchain", Filter). Addmappingforurlpatterns (null, FALSE, "/*");

	}

@Configuration @EnableWebSecurity @Order (2) public class Securityconfiguration extends Websecurityconfigureradapter {@

	autowired private Userdetailsservice Myuserdetailsservice; @Override protected void Configure (Authenticationmanagerbuilder auth) throws Exception {//Auth.inmemoryauthentication
		(). Withuser ("Marissa"). Password ("koala"). Roles ("User"). and (). Withuser ("Paul")//. Password ("EMU"). Roles ("User");
	Auth.userdetailsservice (Myuserdetailsservice); @Override public void Configure (Websecurity Web) throws Exception {web.ignoring (). Antmatchers ("/webjars/**", "/ima
	ges/** ","/oauth/uncache_approvals ","/oauth/cache_approvals ");
	} @Override protected Userdetailsservice Userdetailsservice () {return myuserdetailsservice; @Override @Bean public AuthenticationManager Authenticationmanagerbean () throws Exception {return super.authentic
	Ationmanagerbean (); } @Override protected void Configure (Httpsecurity http) throws Exception {System.out.println ("=============securityconfiguration.configure (httpsecurity http) "); @formatter: Off http. authorizerequests (). Antmatchers ("/login.jsp"). Permit
                All (). Anyrequest (). Hasrole ("USER"). and (). ExceptionHandling ()  . Accessdeniedpage ("/login.jsp?authorization_error=true"). and ()//Todo:put CSRF protection Back to this endpoint. CSRF (). Requirecsrfprotectionmatcher (New Antpathrequestmatcher ("/oau Th/authorize ")). Disable (). Logout (). Logouturl ("/logout "). Logou
                Tsuccessurl ("/login.jsp"). and (). Formlogin (). Loginprocessingurl ("/login")
        . Failureurl ("/login.jsp?authentication_error=true"). LoginPage ("/login.jsp"); @formatter: on}}

2. Configure OAuth

@Configuration public class Oauth2serverconfig {@Configuration @EnableResourceServer @Order (6) protected static Clas S resourceserverconfiguration extends Resourceserverconfigureradapter {@Override public void Configure (Resourceserve
		Rsecurityconfigurer resources) {Resources.resourceid (resourcesids.user_resource_id). stateless (false); @Override public void Configure (Httpsecurity http) throws Exception {System.out.println ("====================re
			Sourceserverconfiguration.configure (httpsecurity http) "); @formatter: Off HTTP//Since We want the protected resources to be accessible the UI as we we need// Session creation to is allowed (it's disabled by default in 2.0.6). Sessionmanagement (). Sessioncreationpolicy (Sessionc reationpolicy.if_required). and (). Requestmatchers (). Antmatchers ("/user/**"). and (). Auth Orizerequests (). Antmatchers ("/user/profile"). Access ("#oauth2. Hasscope (' read ') or(! #oauth2. Isoauth () and Hasrole (' Role_user ')); @formatter: on}} @Configuration @EnableAuthorizationServer protected static class Authorizationserverconfigura tion extends Authorizationserverconfigureradapter {@Autowired @Qualifier ("Myclientdetailsservice") Private clientde

		Tailsservice Clientdetailsservice;

		@Autowired private Tokenstore Tokenstore;

		@Autowired private Userapprovalhandler Userapprovalhandler;

		@Autowired @Qualifier ("Authenticationmanagerbean") private AuthenticationManager AuthenticationManager; @Override public void Configure (Clientdetailsserviceconfigurer clients) throws Exception {clients.withclientdetails (
		Clientdetailsservice); @Override public void Configure (Authorizationserverendpointsconfigurer endpoints) throws Exception {ENDPOINTS.T
			Okenstore (Tokenstore). Userapprovalhandler (Userapprovalhandler). AuthenticationManager (AuthenticationManager); * *. pathmapping ("/oauth/authorize", "/oauth2/authoRize ") *. pathmapping ("/oauth/token ","/oauth2/token "); *////above the annotation is used to change the configuration of the} @Override public void Configure (Authorizationserversecurityconfigurer oauthserver) throw
			s Exception {//Oauthserver.realm ("sparklr2/client");
		Oauthserver.allowformauthenticationforclients ();
		@Bean public Tokenstore Tokenstore () {return new Inmemorytokenstore ();  }/** * @author Admin * * * some bean denfinition * */@Configuration protected static class Stuff

		{@Autowired @Qualifier ("Myclientdetailsservice") 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 Myuserapprovalhandler Userapprovalhandler () Throws Exception {MyuserapprovalhanDler handler = new Myuserapprovalhandler ();
			Handler.setapprovalstore (Approvalstore ());
			Handler.setrequestfactory (New Defaultoauth2requestfactory (Clientdetailsservice));
			Handler.setclientdetailsservice (Clientdetailsservice);
			Handler.setuseapprovalstore (TRUE);
		return handler; }
	}

The above is based on the annotation configuration

Be sure to note: Resourceserverconfiguration and Securityconfiguration on the order of configuration, securityconfiguration must be before resourceserverconfiguration , because spring implementation security is implemented by adding filters (filter), the basic security filtering should be before OAuth filtering, so set @order (2) in Securityconfiguration, Set @order on Resourceserverconfiguration (6)


Other classes:

Myuserapprovalhandler.java

public class Myuserapprovalhandler extends Approvalstoreuserapprovalhandler {private Boolean useapprovalstore = true;

	Private Clientdetailsservice Clientdetailsservice;
	 /** * Service to load client details (optional) for auto approval checks. * * @param clientdetailsservice * A Client details service/public void Setclientdetailsservice (Clien
		Tdetailsservice clientdetailsservice) {this.clientdetailsservice = Clientdetailsservice;
	Super.setclientdetailsservice (Clientdetailsservice); }/** * @param useapprovalstore * The usetokenservices to set */public void Setuseapprovalstore (Boole
	An useapprovalstore) {this.useapprovalstore = Useapprovalstore;
	 }/** * Allows automatic approval for a white list of clients in the implicit * grant case.
	 * * @param authorizationrequest * The authorization request. * @param userauthentication * The current user authentication * * @return a updated requEST if it has already been approved by the current * user. * * @Override public authorizationrequest checkforpreapproval (authorizationrequest authorizationrequest, Authenticati
		On UserAuthentication) {Boolean approved = false; If we are allowed to check existing approvals this'll short circuit//The decision if (Useapprovalstore) {AU
			Thorizationrequest = Super.checkforpreapproval (Authorizationrequest, userauthentication);
		Approved = authorizationrequest.isapproved (); } else {if (Clientdetailsservice!= null) {collection<string> requestedscopes = Authorizationrequest.getsco
				PE ();
					try {clientdetails client = Clientdetailsservice. Loadclientbyclientid (Authorizationrequest.getclientid ());
							for (String scope:requestedscopes) {if (Client.isautoapprove (scope)) {approved = true;
						Break Clientregistrationexception e) {}}} authorizationrequest.setapproved (APproved);

	return authorizationrequest; }

}

Myclientdetailsservice.java

@Service public class Myclientdetailsservice implements Clientdetailsservice {private Clientdetailsservice Clientdetai

	Lsservice; @PostConstruct public void init () {Inmemoryclientdetailsservicebuilder Inmemoryclientdetailsservicebuilder = new Inmem
		Oryclientdetailsservicebuilder ();
			@formatter: Off Inmemoryclientdetailsservicebuilder. Withclient ("Tonr"). Resourceids (resourcesids.user_resource_id). Authorizedgranttypes ("Authorization_code", "impli CIT "). Authorities (" Role_client "). Scopes (" read "," write "). Secret (" secret "). and () withclient (" Tonr-w Ith-redirect "). Resourceids (resourcesids.user_resource_id). Authorizedgranttypes (" Authorization_code "," implicit " 
				). Authorities ("Role_client"). Scopes ("read", "write"). Secret ("secret")//. Redirecturis (Tonrredirecturi) . and (). Withclient ("My-client-with-registered-redirect"). Resourceids (resourcesids.user_resource_id). Auth Orizedgranttypes ("Authorization_code", "Client_credentials "). Authorities (" Role_client "). Scopes (" read "," Trust "). Redirecturis (" Http://anywhere?key=v Alue "). and (). Withclient (" My-trusted-client "). Authorizedgranttypes (" Password "," Authorization_code "," Refresh _token "," implicit "). Authorities (" Role_client "," role_trusted_client "). Scopes (" read "," write "," Trust "). ACC Esstokenvalidityseconds. and (). 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 "). and (). Withclient (" My-less-trusted-client "). Authorizedgran
			Ttypes ("Authorization_code", "implicit"). Authorities ("Role_client"). Scopes ("read", "write", "Trust"). and () 
				. Withclient ("My-less-trusted-autoapprove-client"). Authorizedgranttypes ("implicit"). Authorities ("ROLE_CLIENT") . Scopes ("read", "WRIte "," Trust "). Autoapprove (True);
		@formatter: on try {clientdetailsservice = Inmemoryclientdetailsservicebuilder.build ();
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); @Override public clientdetails Loadclientbyclientid (String clientId) throws Clientregistrationexception {System
		. Out.println ("Loadclientbyclientid:" + clientId + "----------------------");
	Return Clientdetailsservice.loadclientbyclientid (CLIENTID); }

}




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.