"could not obtain access token" error in spring security oauth2 - spring

In my spring project i have an oauth2 client app running on localhost:9999 and an oauth2 authorization server running on localhost:8080.
In result, after approval page, i see error page that i don't know what is the problem?
when press F12 i see that set-cookie done! but /oauth/token not called! and /me also not called! and browser not redirect to localhost:9999.
my client app
package sso.client;
import java.security.Principal;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#EnableAutoConfiguration
#Configuration
#EnableOAuth2Sso
#RestController
public class App {
#RequestMapping("/")
public String home(Principal user) {
return "Hello " + user.getName();
}
public static void main(String[] args) {
new SpringApplicationBuilder(App.class)
.properties("spring.config.name=client").run(args);
}
}
client.yml
server:
port: 9999
security:
oauth2:
client:
client-id: acme
client-secret: acmesecret
access-token-uri: http://localhost:8080/oauth/token
user-authorization-uri: http://localhost:8080/oauth/authorize
resource:
user-info-uri: http://localhost:8080/me
my authorization server
package sso.raymon;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#Configuration
#EnableAutoConfiguration
#RestController
#EnableWebSecurity
public class App extends WebSecurityConfigurerAdapter
{
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
#Configuration
#EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter{
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security)
throws Exception {
// TODO Auto-generated method stub
security.allowFormAuthenticationForClients();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// #formatter:off
clients.inMemory()
.withClient("acme")
.authorizedGrantTypes("authorization_code")
.authorities("ROLE_CLIENT")
.scopes("read", "write")
.secret("acmesecret");
// #formatter:on
}
}
#RequestMapping("/me")
public String home(Principal user) {
return user.getName();
}
#Configuration
#EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/me")
.authorizeRequests().anyRequest().authenticated();
}
}
}
application.properties
security.user.name=forough
security.user.password=m123
Error in blow URL:
localhost:9999/login?code=xZgYwZ&state=27XzVY
Error:
Whitelable Error Page
this application has no explicit mapping for /error, so you are seeing this a fallback.
There was an unexpected erroe (type=Unauthorized, atatus=401).
Authentication Failed: could not obtain access token

Related

Spring Security - Redirect to entered url after success login

I have been working on Spring Security
I use a role based authentication. If the user is admin he will be directed to admindashboard and user will be redirected to his respective dashboard where they share a common login portal.
If a person enters a url of the admin/user dashboard before login it asks the person to login but doesn't redirect to entered url. Instead throws an error "cannot call sendRedirect".
My code for security configuration file
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.util.UrlPathHelper;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired private LoginSuccessHandler loginSuccessHandler;
#Bean
AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider=new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(new BCryptPasswordEncoder());
return provider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/userhome").hasAuthority("USER").
antMatchers("/adminhome").hasAuthority("ADMIN")
.antMatchers("/register").permitAll()
.and().formLogin().loginPage("/login")
.successHandler(loginSuccessHandler)
.permitAll().and().logout().logoutSuccessHandler(new LogoutSuccessHandler() {
#Override
public void onLogoutSuccess(HttpServletRequest request,HttpServletResponse response,Authentication authentication) throws IOException,ServletException{
System.out.println("The User "+authentication.getName() + " has logged out");
UrlPathHelper helper=new UrlPathHelper();
String context=helper.getContextPath(request);
response.sendRedirect(context+"/home");
}
}).permitAll();
http.csrf().disable();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
My Login Successful handler
package strictly.cinema.config;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import strictly.cinema.service.CustomUserDetails;
#Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
Collection<? extends GrantedAuthority> authorities =userDetails.getAuthorities();
authorities.forEach(auth->System.out.println(auth.getAuthority()));
String redirectURL=request.getContextPath();
if(userDetails.hasRole("USER"))
redirectURL+="/userhome";
else if(userDetails.hasRole("ADMIN"))
redirectURL+="/adminhome";
response.sendRedirect(redirectURL);
super.onAuthenticationSuccess(request, response, authentication);
}
}
Overriden the logout handler in the security handler itself.
Need help to store the entered URL once the user is authenticated and eligible to access the URL he should be redirected to the URL after the login
Instead of using successHandler, you could redirect him to a success endpoint as follow :
.defaultSuccessUrl("/loginSuccess")
And the new endpoint will redirect him to "/userhome" or "/adminhome" based on his role.
(Below was not tested)
Success endpoint :
#GetMapping("/loginSuccess")
public void getLoginInfo(
#AuthenticationPrincipal UserDetails authentication,
HttpServletResponse response) throws IOException {
if (authentication.getAuthorities()
.contains(new SimpleGrantedAuthority("ADMIN"))) {
response.sendRedirect("/adminhome");
} else {
response.sendRedirect("/userhome");
}
}

AuthorizationServerConfigurerAdapter cannot be resolved to a type

I have a Spring boot application v 1.5.10 with oauth version 2.0.14
I want to create a configuration file to implement AuthorizationServerConfigurerAdapter interface to generate access token from
package com.razzanati.oauth2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
#Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("client")
.secret(passwordEncoder().encode("password"))
.scopes("all")
.authorizedGrantTypes("client_credentials")
.and()
.withClient("client_b")
.secret(passwordEncoder().encode("password_b"));
}
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
#Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder(4);
}
}
This is what I've got:
The import org.springframework.security.oauth2 cannot be resolved
AuthorizationServerConfigurerAdapter cannot be resolved to a type
Any idea?

Spring security Azure active directory

Could you please suggest how to increase the timeout. I am getting below exception and this is not coming every time. I have Angular 5 as front end and in back end using Spring Boot 2.0.4 and azure active directory release 2.0.5 (latest).
com.nimbusds.jose.RemoteKeySourceException: Couldn't retrieve remote JWK set: Read timed out.Below is my source code.
Thank in advance.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.microsoft.azure.spring.autoconfigure.aad.AADAuthenticationFilter;
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AADAuthenticationFilter aadAuthFilter;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/ppo/dashboard/dashboardstats").permitAll();
http.authorizeRequests().antMatchers("/api/ppo/dashboard/castats").permitAll();
http.authorizeRequests().antMatchers("/api/ppo/authenticate/privileges").permitAll();
http.authorizeRequests().antMatchers("/api/ppo/**").authenticated();
//http.authorizeRequests().antMatchers("/api/ppo/autenticate/**").permitAll();
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").deleteCookies("JSESSIONID").invalidateHttpSession(true);
//http.authorizeRequests().anyRequest().permitAll();
http.csrf().disable();
http.cors();
// http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
http.addFilterBefore(aadAuthFilter, UsernamePasswordAuthenticationFilter.class);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/ppo/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}

SpringBoot+REST+Security - either all access open or all closed

What I am trying to do should be pretty easy:
a REST-Service with 3 different security levels:
A "public" RestService accessible by all
A "protected" RestService for "USER"s
A "private" RestService for "ADMIN"s
but either I have Access to all - or with the current config I got acces to NONE, because Without BasicAuth I always got
Full authentication is required to access this resource
and with the "uuu" + "ppp" I always got
Bad credentials
By the way I using spring boot 1.5.3
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
#Configuration
#EnableWebSecurity
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("aaa").password("ppp").roles("USER", "ADMIN");
auth.inMemoryAuthentication().withUser("uuu").password("ppp").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/protected/**").hasRole("USER")
.antMatchers("/private/**").hasRole("ADMIN")
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // We don't need sessions to be created.
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**"); /* To allow Pre-flight [OPTIONS] request from browser */
}
}
The OP found their solution actually works. There was a problem with the component-Scan, because my Rest project is a child of my DAO and Repository-Project...
#SpringBootApplication
#EnableAutoConfiguration
#ComponentScan({"com.leycarno.base", "com.leycarno.rest"}) // now we're listen to all the nice components :-)
#EnableJpaRepositories("com.leycarno.base.repositories")
#EntityScan("com.leycarno.base.models")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Spring Oauth2 not working for me - Status Not Answered

I am trying out Oauth2 with Spring security. I am trying to call the /getresource service in my resource class by following the below
GET http://localhost:8080/oauth/authorize?
response_type=code
&client_id=my-first-client
&redirect_url=http://localhost:8080/getcode
&scope=read
Get the code and call the Authorization service to get the auth token by doing
POST http://localhost:8080/oauth/token
grant_type=authorization_code&code=XXXX
Get the token and call the /getresource rest service.
by
GET http://localhost:8080/getresource
Header : Authorization: Bearer <>
But I have been getting the below error
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
Any help will to locate the issue will be greatly appreciated.
My Authorization class
package auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
#EnableAuthorizationServer
#SpringBootApplication
#EnableWebSecurity
public class AuthProvider extends WebSecurityConfigurerAdapter implements AuthorizationServerConfigurer{
#Autowired
AuthenticationManager authenticationManager;
#Autowired
DriverManagerDataSource dataSource;
public static void main(String[] args)
{
SpringApplication.run(AuthProvider.class, args);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
String uname_query = "select username,userpass,enabled from users where username=?";
String role_query = "Select username, role_name from user_roles where username=?";
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(uname_query)
.authoritiesByUsernameQuery(role_query);
}
/* #Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/login","/home","/403","/oauth/**","/resources/**").permitAll()
.antMatchers("/getresource").access("#oauth2.hasScope('read')")
.anyRequest().authenticated().and().formLogin().loginPage("/login");
}*/
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// TODO Auto-generated method stub
security.allowFormAuthenticationForClients();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("my-first-client")
.secret("password")
.accessTokenValiditySeconds(120)
.authorizedGrantTypes("authorization_code", "refresh_token","password")
.authorities("ROLE_CLIENT")
.redirectUris("http://localhost:8080/authcode")
.resourceIds("testresource");
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// TODO Auto-generated method stub
endpoints.authenticationManager(authenticationManager);
}
}
My Resource class
package auth;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#Configuration
#EnableResourceServer
#RestController
public class Resource {
private static final String resourceid="testresource";
#RequestMapping("/getresource")
public String getResource()
{
return "Hello Everyone!!";
}
private static class Resourceconfigurator extends ResourceServerConfigurerAdapter
{
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(Resource.resourceid);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/login","/home","/403","/oauth/**","/resources/**").permitAll()
.antMatchers("/getresource").access("#oauth2.hasScope('read')")
.anyRequest().authenticated().and().formLogin().loginPage("/login");
}
}
}

Resources