Multiple authentification strategies in spring boot security
In order to use a custom authentification in spring security you got to implement the UserDetailsService
interface and override the loadUserByUsername
method, such as the example below
public class UserServiceImpl implements UserDetailsService{
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String useremail)
throws UsernameNotFoundException {
Users user = userDao.findByUserEmail(useremail);
if(user == null){
throw new UsernameNotFoundException("UserName or Password Invalid.");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, getGrantedAuthorities(userDao.getUserRole(user.getUsersId())));
}
and its working fine for the whole website.
what i want to do now is to expose a restful webservice from the same host and all the requests for that WS will be through the /api/**
with a different type of authentification (e.g : using tokens)
is it possible to do it? and if so, is there any idea how to do it ? any useful resources ?
java spring authentication spring-security token
add a comment |
In order to use a custom authentification in spring security you got to implement the UserDetailsService
interface and override the loadUserByUsername
method, such as the example below
public class UserServiceImpl implements UserDetailsService{
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String useremail)
throws UsernameNotFoundException {
Users user = userDao.findByUserEmail(useremail);
if(user == null){
throw new UsernameNotFoundException("UserName or Password Invalid.");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, getGrantedAuthorities(userDao.getUserRole(user.getUsersId())));
}
and its working fine for the whole website.
what i want to do now is to expose a restful webservice from the same host and all the requests for that WS will be through the /api/**
with a different type of authentification (e.g : using tokens)
is it possible to do it? and if so, is there any idea how to do it ? any useful resources ?
java spring authentication spring-security token
add a comment |
In order to use a custom authentification in spring security you got to implement the UserDetailsService
interface and override the loadUserByUsername
method, such as the example below
public class UserServiceImpl implements UserDetailsService{
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String useremail)
throws UsernameNotFoundException {
Users user = userDao.findByUserEmail(useremail);
if(user == null){
throw new UsernameNotFoundException("UserName or Password Invalid.");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, getGrantedAuthorities(userDao.getUserRole(user.getUsersId())));
}
and its working fine for the whole website.
what i want to do now is to expose a restful webservice from the same host and all the requests for that WS will be through the /api/**
with a different type of authentification (e.g : using tokens)
is it possible to do it? and if so, is there any idea how to do it ? any useful resources ?
java spring authentication spring-security token
In order to use a custom authentification in spring security you got to implement the UserDetailsService
interface and override the loadUserByUsername
method, such as the example below
public class UserServiceImpl implements UserDetailsService{
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String useremail)
throws UsernameNotFoundException {
Users user = userDao.findByUserEmail(useremail);
if(user == null){
throw new UsernameNotFoundException("UserName or Password Invalid.");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, getGrantedAuthorities(userDao.getUserRole(user.getUsersId())));
}
and its working fine for the whole website.
what i want to do now is to expose a restful webservice from the same host and all the requests for that WS will be through the /api/**
with a different type of authentification (e.g : using tokens)
is it possible to do it? and if so, is there any idea how to do it ? any useful resources ?
java spring authentication spring-security token
java spring authentication spring-security token
edited Nov 21 '18 at 10:00
octopus
asked Nov 21 '18 at 9:48


octopusoctopus
2817
2817
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
You can start by making security configuration class as follows
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
And your TokenAuthenticationFilter class will do the token authenticity for every request.
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern/api/**
, and apply another authentification (email,password) for the other requests
– octopus
Nov 22 '18 at 8:45
So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359
– Shashank Rajput
Nov 22 '18 at 9:36
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53409262%2fmultiple-authentification-strategies-in-spring-boot-security%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can start by making security configuration class as follows
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
And your TokenAuthenticationFilter class will do the token authenticity for every request.
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern/api/**
, and apply another authentification (email,password) for the other requests
– octopus
Nov 22 '18 at 8:45
So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359
– Shashank Rajput
Nov 22 '18 at 9:36
add a comment |
You can start by making security configuration class as follows
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
And your TokenAuthenticationFilter class will do the token authenticity for every request.
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern/api/**
, and apply another authentification (email,password) for the other requests
– octopus
Nov 22 '18 at 8:45
So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359
– Shashank Rajput
Nov 22 '18 at 9:36
add a comment |
You can start by making security configuration class as follows
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
And your TokenAuthenticationFilter class will do the token authenticity for every request.
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
You can start by making security configuration class as follows
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
And your TokenAuthenticationFilter class will do the token authenticity for every request.
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationFilter tokenAuthenticationFilter;
...
public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
this.corsFilter = corsFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and()
.addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(You log out success handler goes here)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
edited Nov 22 '18 at 8:03
answered Nov 22 '18 at 6:20


Shashank RajputShashank Rajput
1125
1125
I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern/api/**
, and apply another authentification (email,password) for the other requests
– octopus
Nov 22 '18 at 8:45
So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359
– Shashank Rajput
Nov 22 '18 at 9:36
add a comment |
I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern/api/**
, and apply another authentification (email,password) for the other requests
– octopus
Nov 22 '18 at 8:45
So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359
– Shashank Rajput
Nov 22 '18 at 9:36
I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern
/api/**
, and apply another authentification (email,password) for the other requests– octopus
Nov 22 '18 at 8:45
I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern
/api/**
, and apply another authentification (email,password) for the other requests– octopus
Nov 22 '18 at 8:45
So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359
– Shashank Rajput
Nov 22 '18 at 9:36
So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359
– Shashank Rajput
Nov 22 '18 at 9:36
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53409262%2fmultiple-authentification-strategies-in-spring-boot-security%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown