In case if you missed it, here is the place to grab.
http://blog.rajithdelantha.com/2015/09/secure-your-rest-api-with-spring.html
Spring boot is one of the new inventions from Spring framework that makes developers' lives easier when building large scale applications. Here is a good place to grab the concepts.
If you check my previous post related to oauth2 security then you know there is a bit of configuration that needs to be done in Spring side. But on the other hand Spring boot will do all the hard work and we just need to tell them what to do by a simple annotation.
So this post is about how to configure Spring boot project with Spring security and Oauth2. Actually we can't really say configure because all most all configurations are done by Spring boot itself.
Source code : https://github.com/rajithd/spring-boot-oauth2
Step 1
For this project I'm using H2 in memory database. Because of that you don't need to create any database and tables as the creation happens at run time. But if you want this project to use MySQL as the data source then first create the database and then create the tables.
CREATE TABLE user (
username VARCHAR(50) NOT NULL PRIMARY KEY,
email VARCHAR(50),
password VARCHAR(500),
activated BOOLEAN DEFAULT FALSE,
activationkey VARCHAR(50) DEFAULT NULL,
resetpasswordkey VARCHAR(50) DEFAULT NULL
);
CREATE TABLE authority (
name VARCHAR(50) NOT NULL PRIMARY KEY
);
CREATE TABLE user_authority (
username VARCHAR(50) NOT NULL,
authority VARCHAR(50) NOT NULL,
FOREIGN KEY (username) REFERENCES user (username),
FOREIGN KEY (authority) REFERENCES authority (name),
UNIQUE INDEX user_authority_idx_1 (username, authority)
);
CREATE TABLE oauth_access_token (
token_id VARCHAR(256) DEFAULT NULL,
token BLOB,
authentication_id VARCHAR(256) DEFAULT NULL,
user_name VARCHAR(256) DEFAULT NULL,
client_id VARCHAR(256) DEFAULT NULL,
authentication BLOB,
refresh_token VARCHAR(256) DEFAULT NULL
);
CREATE TABLE oauth_refresh_token (
token_id VARCHAR(256) DEFAULT NULL,
token BLOB,
authentication BLOB
);
- user table - system users
- authority - roles
- user_authority - many to many table for user and role
- oauth_access_token - to hold access_token
- oauth_refresh_token - to hold refresh_token
Add some seed data.
INSERT INTO user (username,email, password, activated) VALUES ('admin', 'admin@mail.me', 'b8f57d6d6ec0a60dfe2e20182d4615b12e321cad9e2979e0b9f81e0d6eda78ad9b6dcfe53e4e22d1', true);
INSERT INTO user (username,email, password, activated) VALUES ('user', 'user@mail.me', 'd6dfa9ff45e03b161e7f680f35d90d5ef51d243c2a8285aa7e11247bc2c92acde0c2bb626b1fac74', true);
INSERT INTO user (username,email, password, activated) VALUES ('rajith', 'rajith@abc.com', 'd6dfa9ff45e03b161e7f680f35d90d5ef51d243c2a8285aa7e11247bc2c92acde0c2bb626b1fac74', true);
INSERT INTO authority (name) VALUES ('ROLE_USER');
INSERT INTO authority (name) VALUES ('ROLE_ADMIN');
INSERT INTO user_authority (username,authority) VALUES ('rajith', 'ROLE_USER');
INSERT INTO user_authority (username,authority) VALUES ('user', 'ROLE_USER');
INSERT INTO user_authority (username,authority) VALUES ('admin', 'ROLE_USER');
INSERT INTO user_authority (username,authority) VALUES ('admin', 'ROLE_ADMIN');
Step 2
Configure WebSecurityAdapter
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new StandardPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/h2console/**")
.antMatchers("/api/register")
.antMatchers("/api/activate")
.antMatchers("/api/lostpassword")
.antMatchers("/api/resetpassword");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
}
Step 3
Configuration for Oauth2
@Configuration
public class OAuth2Configuration {
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
@Autowired
private CustomLogoutSuccessHandler customLogoutSuccessHandler;
@Override
public void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.and()
.logout()
.logoutUrl("/oauth/logout")
.logoutSuccessHandler(customLogoutSuccessHandler)
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.headers()
.frameOptions().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/hello/**").permitAll()
.antMatchers("/secure/**").authenticated();
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {
private static final String ENV_OAUTH = "authentication.oauth.";
private static final String PROP_CLIENTID = "clientid";
private static final String PROP_SECRET = "secret";
private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";
private RelaxedPropertyResolver propertyResolver;
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(propertyResolver.getProperty(PROP_CLIENTID))
.scopes("read", "write")
.authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
.authorizedGrantTypes("password", "refresh_token")
.secret(propertyResolver.getProperty(PROP_SECRET))
.accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
}
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
}
}
}
This is it. Try running Spring boot application by
mvn spring-boot:run
Then check your oauth2 security by executing following curls.
https://github.com/rajithd/spring-boot-oauth2
Thank you for sharing the information. And please update some useful article like this.
ReplyDeletedigital marketing training Chennai
Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training
DeleteHibernate Online Training Hibernate Online Training Spring Online Training Spring Online Training Spring Batch Training Online Spring Batch Training Online
Spring online training Spring online training Spring Hibernate online training Spring Hibernate online training Java online training
Deletespring training in chennai spring hibernate training in chennai
Java Training Institutes Java Training Institutes JMS Training Institutes in Chennai JMS Training Institutes in Chennai | JSP Training Institutes in Chennai | MicroServices Training Institutes In Chennai Java MicroServices Training Institutes In Chennai
DeleteGreat Article
DeleteIEEE Final Year Projects for CSE Final Year Project Centers in Chennai
I am reading the articles one by one since yesterday night and every time i find a new article grabbing my attention within a post.
ReplyDeleteiOS Training in Chennai
I have read your blog its very attractive and impressive. I like it your blog.
DeleteDigital Marketing Company in Chennai Digital Marketing Agency
SEO Company in India SEO Services in India
I read this book really awesome.You provided another one great article.I hope this information may change my carrier.
ReplyDeleteOracle SQL Training in Chennai
Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.
ReplyDeleteWeb Designing Training in Chennai
Nice article, is it possible SSO using spring oauth2 framework authorization and authentication please provide some example code
ReplyDeleteThe future of software testing is on positive note. It offers huge career prospects for talented professionals to be skilled software testers. Best software testing training institute in Chennai | Software Testing Training in Chennai | Software testing course in Chennai
ReplyDeleteIt’s really amazing that we can record what our visitors do on our site. Thanks for sharing this awesome guide. I’m happy that I came across with your site this article is on point,thanks again and have a great day.
ReplyDeleteMicrostrategy Training in Chennai
You made some decent factors there. I looked on the internet for the difficulty and found most individuals will associate with along with your website.Keep update more excellent posts.
ReplyDeleteDigital marketing company in Chennai
Really an amazing post..! By reading your blog post i gained more information. Thanks a lot for posting unique information and made me more knowledgeable person. Keep on blogging!!
ReplyDeleteHadoop Training in Chennai Adyar
I do believe all of the concepts you’ve introduced in your post. They’re very convincing and will definitely work. Nonetheless, the posts are too short for novices. May you please extend them a bit from subsequent time? Thank you for the post.
ReplyDeleteOnline Training in Chennai
ReplyDeleteI do trust all of the concepts you’ve presented on your post. They’re really convincing and will definitely work. Still, the posts are too brief for newbies. May you please extend them a little from subsequent time?Also, I’ve shared your website in my social networks.
Corporate Training in Chennai
Great information shared in this blog. Helps in gaining concepts about new information and concepts.Awsome information provided.Very useful for the beginners.
ReplyDeleteDotnet Training in Chennai
Nice Blog
ReplyDeleteTelugu70mm.com Provides Latest Telugu Movie Reviews and other news like Telugu Movie News , Telugu Political News and Movie Released Dates
Wow amazing i saw the article with execution models you had posted. It was such informative.By explaining this type we can identify the concepts easily. So thank you for this sharing.
ReplyDeleteSEO Training in Chennai
Great information shared in this blog. Helps in gaining concepts about new information and concepts.Awsome information provided.Very useful for the beginners.
ReplyDeleteSEO training in Chennai
very useful information provided in this blog. concepts were explained in a detailed manner. Keep giving these types of information.
ReplyDeleteSEO training in Chennai
Wow really nice and by explaining with execution models we can easily interact with the concepts as well. And within this how it will be enabled with API systems? Other than that i am okey and if you are having some other suggestion mean share that please.
ReplyDeleteCar Wash Services in Mumbai
Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
ReplyDeleteRegards,
SAP Training in Chennai with placement | java training in chennai with placement
We appreciate, result in I ran across what exactly I had been seeking. You could have wrapped up my own Some evening extended quest! Our god Bless you man. Use a fantastic time. Ok bye
ReplyDeleteApp-v Online Training By Realtime Trainer In India
Dellboomi Online Training By Realtime Trainer In India
Hadoop Online Training By Realtime Trainer In India
My SQL Online Training By Realtime Trainer In India
The blog gave me idea about spring boot
ReplyDeleteHadoop Training in Chennai
This blog having the details of Processes running. The way of running is explained clearly. The content quality is really great. The full document is entirely amazing. Thank you very much for this blog.
ReplyDeleteSEO Company in India
Digital Marketing Company in India
A nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
ReplyDeleteBest Laser Clinic In Chennai
Best Implant Clinic In Chennai
Thank you for sharing the information here. Its much informative and really i got some valid information. You had posted the amazing article.
ReplyDeleteMSBI Training in Chennai
Informatica Training in Chennai
Dataware Housing Training in Chennai
This blog having the details of Processes running. The way of running is explained clearly. The content quality is really great. The full document is entirely amazing. Thank you very much for this blog.
ReplyDeleteAndroid Training Institute in Chennai
Thanks for sharing such informative article. Know about Know about English to Tamil from techfizy.
ReplyDeleteNice information. Thank you for sharing such post...!
ReplyDeleteVery nice post. Awesome article... Really helpful...!
ReplyDeleteThanks this article, This save my time. Thanks.
ReplyDeleteThank You For Posting, Its A Nice Blog.
ReplyDeleteBest SAP Training in Bangalore
Best Java Training in Bangalore
very nice post
ReplyDeleteAwesome article
ReplyDeleteReally useful.
ReplyDeleteInformative. Thank you for sharing
ReplyDeletevery nice blog It was useful
ReplyDeletevery nice blog It was useful
ReplyDeleteIts a nice post.
ReplyDeleteBest Oracle Training in Bangalore
Nice Blog.
ReplyDeleteAdvanced Digital Marketing Course in Bangalore
This is very good blog for learners, Thanks for sharing valuable content on MSBI Online Training
ReplyDeleteThanks for the informative article. This is one of the best resources I have found in quite some time.Nicely written and great info. I really cannot thank you enough for sharing.
ReplyDeleteHerbalife in chennai
wellnesscoaches in chennai
Weightloss in chennai
Weightgain in chennai
Decent data. Your blog is extremely useful. Great work!
ReplyDeleteseo company in bangladesh
Phenomenal and supportive article.
ReplyDeleteread more
In your article, focuses grabbed my eye the most is the manner by which your writing, to give me a profound impression. Wish you would compose more. good fortunes!
ReplyDeleteiPhone cases
Technology is updated day to day
ReplyDeleteThanks for sharing the info, Salesforce is the best platform for all organizations to perform the multiple tasks at a time
Best Salesforce online Training
Salesforce Training online in India
Salesforce Online Training in Bangalore
After I read and try to understand this article in conclusion amazingwe are generally grateful for the nearness of this article can incorporate impressively more learning for each one of us. thankful to you.
ReplyDeleteAccountants Brighton
I've been surfing on the web over 3 hours today, yet I never found any fascinating article like yours. It's enough worth for me. As I would see it, if all web proprietors and bloggers made exceptional substance as you did, the net will be basically more productive than at whatever point in late memory.
ReplyDeleteBrighton Accountants
Amazing and extremely cool thought and the subject at the highest point of brilliance and I am cheerful to this post..Interesting post! Much obliged for composing it. What's the issue with this sort of post precisely? It takes after your past rule for post length and in addition clearness
ReplyDeleteTax Advisors
Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
ReplyDeleteSelenium Training in Bangalore | Selenium Training in Bangalore | Selenium Training in Bangalore | Selenium Training in Bangalore
Data science is a fast-moving field – if you’re pursuing a data science career, or even if you’re just interested in data-related topics, you need to invest time to keep up with the trends. Following a few top blogs is a great way to stay abreast of developments in data analysis, statistical software, data visualization, and more. These AUTOMATIONMINDS bloggers consistently offer great resources and tutorials, along with opportunities to connect with and learn from other leading data science professionals.
ReplyDeleteDATA SCIENCE training in chennai
SQream Technologies provides you with a state of the art software which combines modern GPU technology (Graphic Processing Units) with the best practices in today’s Big Data platforms, providing up to 100x faster insights from data.
ReplyDeleteBigdata Training in Chennai OMR