Spring Security oauth2 JWT authentication and resource separation configuration file (Java class configuration version)

Source: Internet
Author: User
Tags oauth

Learn more about Spring security oauth2 recently. Download the official examples of SPARKLR2 and TONR2 to learn. But the examples contain too many things to know what the simplest and most important configurations are. So I decided to try to build a simple version of the example. Learn the process of building certifications and resources in a project example, storing tokens in database examples and so on. Finally, this certified and resource-separated JWT tokens version was made. Find some available code on the web and then do a collation, and test which code is required. There may still be some unnecessary code in, welcome to enlighten us.

One. Create three spring boot projects, adding the necessary dependencies, respectively. Certification and resource engineering need to add dependency <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.7.RELEASE</version>
</dependency>

Resource configuration files for two-resource-side projects:

@Configuration
@EnableResourceServer
public class Oauth2resourceservice extends Resourceserverconfigureradapter {
private static final String sparklr_resource_id = "Apple";

@Override
public void Configure (Resourceserversecurityconfigurer resources) {
Resources.tokenservices (Tokenservices ()). ResourceId (sparklr_resource_id);
}
@Bean
Public Tokenstore Tokenstore () {
return new Jwttokenstore (Accesstokenconverter ());
}
@Bean
Public Jwtaccesstokenconverter Accesstokenconverter () {
Jwtaccesstokenconverter converter = new Jwtaccesstokenconverter ();
Converter.setsigningkey ("123");
return converter;
}
@Bean
@Primary
Public Defaulttokenservices tokenservices () {
Defaulttokenservices defaulttokenservices = new Defaulttokenservices ();
Defaulttokenservices.settokenstore (Tokenstore ());
return defaulttokenservices;
}

@Override
public void Configure (Httpsecurity http) throws Exception {
@formatter: Off
http
. Authorizerequests ()
. Antmatchers ("/hello"). Access ("#oauth2. Hasscope (' read ') or (! #oauth2. Isoauth () and Hasrole (' Role_user '))");
@formatter: On
}
}

Security configuration file:

@Configuration
@EnableGlobalMethodSecurity (prepostenabled = True)
@EnableWebSecurity
public class Securityconfig extends Websecurityconfigureradapter {

@Override
protected void Configure (Httpsecurity http) throws Exception {
http
. Authorizerequests ()
. Antmatchers ("/hello"). Hasrole ("USER")
. and (). CSRF (). Disable ()
. Formlogin (). LoginPage ("/login"). Failureurl ("/login-error");
}
@Autowired
public void Configureglobal (Authenticationmanagerbuilder auth) throws Exception {
Auth
. Inmemoryauthentication ()
. Withuser ("Hello"). Password ("123"). Roles ("USER");
}
}

Certification profile for three certification end projects:

@Configuration
@EnableAuthorizationServer
public class Oauth2authorizationserver extends Authorizationserverconfigureradapter {
private static final String sparklr_resource_id = "Apple";

int accesstokenvalidityseconds = 3600;

@Autowired
@Qualifier ("Authenticationmanagerbean")
Private AuthenticationManager AuthenticationManager;

@Bean
Public Jwtaccesstokenconverter Accesstokenconverter () {
Jwtaccesstokenconverter converter = new Jwtaccesstokenconverter ();
Converter.setsigningkey ("123");
return converter;
}

@Override
public void Configure (Clientdetailsserviceconfigurer clients) throws Exception {

@formatter: Off
Clients.inmemory (). Withclient ("Tonr")
. Resourceids (SPARKLR_RESOURCE_ID)
. Authorizedgranttypes ("Authorization_code", "implicit")
. Authorities ("Role_client")
. Scopes ("read", "write")
. Secret ("secret")
. Accesstokenvalidityseconds (Accesstokenvalidityseconds);
@formatter: On
}
Jdbc
@Bean
Public DataSource Jdbctokendatasource () {
Drivermanagerdatasource DataSource = new Drivermanagerdatasource ();
Datasource.setdriverclassname ("com. MySQL.jdbc.Driver ");
Datasource.seturl ("Jdbc:mysql://localhost/test");
Datasource.setusername ("root");
Datasource.setpassword ("root");
return dataSource;
//    }

@Bean
Public Tokenstore Tokenstore () {
return new Inmemorytokenstore ();
return new Jdbctokenstore (Jdbctokendatasource ());
return new Jwttokenstore (Accesstokenconverter ());
}

@Override
public void Configure (Authorizationserverendpointsconfigurer endpoints) throws Exception {
Endpoints.tokenstore (Tokenstore ())
. AuthenticationManager (This.authenticationmanager)
. Accesstokenconverter (Accesstokenconverter ());
}
@Bean
@Primary
Public Defaulttokenservices tokenservices () {
Defaulttokenservices defaulttokenservices = new Defaulttokenservices ();
Defaulttokenservices.settokenstore (Tokenstore ());
Defaulttokenservices.setsupportrefreshtoken (TRUE);
return defaulttokenservices;
}
}\

Spring Security configuration file:

@EnableWebSecurity
public class Securityconfig extends Websecurityconfigureradapter {

@Override
protected void Configure (Httpsecurity http) throws Exception {
http
. Authorizerequests ()
. Antmatchers ("/css/**", "/index"). Permitall ()
. and ()
. CSRF ()
. Requirecsrfprotectionmatcher (New Antpathrequestmatcher ("/oauth/authorize"))
. Disable ()
. Formlogin (). LoginPage ("/login"). Failureurl ("/login-error");
}
@Autowired
public void Configureglobal (Authenticationmanagerbuilder auth) throws Exception {
Auth
. Inmemoryauthentication ()
. Withuser ("Hello"). Password ("123"). Roles ("USER");
}
@Override
@Bean
Public AuthenticationManager Authenticationmanagerbean () throws Exception {
return Super.authenticationmanagerbean ();
}
}

Four client-side project configuration files:

@Configuration
@EnableOAuth2Client
public class Resourceconfiguration {

@Bean
Public Oauth2protectedresourcedetails Hello () {
Authorizationcoderesourcedetails details = new Authorizationcoderesourcedetails ();
Details.setid ("Hello");
Details.setclientid ("Tonr");
Details.setclientsecret ("secret");
Details.setaccesstokenuri ("Http://localhost:8083/auth/oauth/token");//authentication server address +/oauth/token
Details.setuserauthorizationuri ("http://localhost:8083/auth/oauth/authorize");//authentication server address +/oauth/authorize
Details.setscope (Arrays.aslist ("read", "write"));
return details;
}

@Bean
Public oauth2resttemplate helloresttemplate (Oauth2clientcontext oauth2context) {// Client-side information is encapsulated into oauth2resttemplate for requesting resources
return new Oauth2resttemplate (hello (), oauth2context);
}
}

Inject helloresttemplate into the Serviceimp class of the business logic and then:

@Autowired
Private Restoperations Helloresttemplate

Public String Getdatafromresoureserver () {;

String data= Helloresttemplate.getforobject (uri.create ("Http://localhost:8080/resource/hello"), string.class);// Request path to Resource server resource

return data;

}

Spring Security configuration file:

@Configuration
@EnableWebSecurity
public class Securityconfig extends Websecurityconfigureradapter {

@Override
protected void Configure (Httpsecurity http) throws Exception {
http
. Authorizerequests ()
. Antmatchers ("/css/**", "/index"). Permitall ()
. and ()
. Formlogin ()
. LoginPage ("/login"). Failureurl ("/login-error");
}

@Autowired
public void Configureglobal (Authenticationmanagerbuilder auth) throws Exception {
Auth
. Inmemoryauthentication ()
. Withuser ("insecure"). Password ("123"). Roles ("USER");
}
}

http://blog.csdn.net/u010139801/article/details/68484090

Spring Security oauth2 JWT authentication and resource separation configuration file (Java class configuration version)

Related Article

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.