password for oauth token endpoint - java

I am trying to add OAuth to a rest service that I am developing with Spring framework. I am using annotation based configuration and spring-boot to get it running.
I have the following class in my project:
#Configuration
#EnableWebSecurity
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecuritySettings extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("123").authorities("ROLE_USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and().httpBasic().and().csrf().disable();
}
}
and my authorization server configuration is as follows:
#Configuration
#EnableAuthorizationServer
public static class MyAuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("web")
.authorizedGrantTypes("password")
.authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT","ROLE_USER")
.scopes("read", "write")
.resourceIds(RESOURCE_ID);
}
}
When I make a GET request to /oauth/token/ end point I am asked to enter HTTP basic credentials. When I try to login with the admin user then the following is logged
o.s.s.o.provider.endpoint.TokenEndpoint : Handling error: NoSuchClientException, No client with requested id: admin
Entering username as web works, but I don't know the password for it. A default password is logged but it doesn't work either.
Using default security password: f23087f8-58ce-e3d-bc62-58bf0963e75c
So what is this password? Where can I find it? How can I set it?

The API you are using is from this builder class.
The token endpoint is used by client applications to request access tokens for resources. It isn't used by browser end users. OAuth2 clients are usually allocated a "client secret" which they can use to authenticate at the endpoint, generally with Basic authentication as described in the OAuth 2.0 spec.
So to answer your specific question, you would use the "secret" method on the builder API, and use the value to authenticate as the client:
clients.inMemory().withClient("web")
.authorizedGrantTypes("password")
.secret("webclientsecret")
...
Also, the "password" grant means that the client requests tokens using an end users ID and password, just to make sure that's what you actually intend. It's not related to the password issue here.

This is the OAuth access token. It is based on user login and password and used to access protected resources.
URL "/oauth/token" is used to fetch access tokens instead of available Request Token. This request is digitally signed on the basis of Request Token secret.
The Oauth protocol uses this access tokens in this way:
Application-Consumer gets Request Token.
User is redirected on the Service Provider's site and authorizes Request Token there. (If authorization is made via Http basic, then you should add request header with name "Authorization" and value "Basic EncodeBase64("name:password")", where EncodeBase64 is a function, "name" and "password" are user name and user password.
Application-Consumer exchanges Request Token on Access Token.
Application-Consumer sends authorized requests to the service's API.
You can't find additional info in OAuth 2 Developers Guide and Spring Social Reference
I hope you've got answer to your question(or get closer to it). =)

Related

Basics of Spring Security

What are the very basics of Spring Security i.e. how Spring sets up security internally. What are all the beans involved that are to be provided for Spring Security to work out-of-the-box?
I shall start first by explaining, how to bring in Spring Security into your application.
Just add below dependency to your application. Now, when you run your application the spring security is implemented by default. (As of April 2021, version might change in future)
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.4.5</version>
</dependency>
Closely looking at the console, you will see a password generated for default user: user. The password is a hash that you need to use.
When you access any URL from your application now, you will be restricted from Postman. From your browser, you will see a login page where you need to enter this username and password and you will be through to your URL. That sets up the inbuilt Spring Security.
But what is happening under the hood?
I shall answer it by reminding you of Servlets and Filters and DispatcherServlet in Spring.
DispatcherServlet is the very basic of Spring MVC and it forwards the requests to your controllers. Basically, DispatcherServlet is also a servlet.
I can create a chain of filters before DispatcherServlet and check my request for Authentication and Authorization before forwarding the request to hit my DispatcherServlet and then my controllers. This way, I can bring in Security to my application. This is exactly what the Spring Security does.
The below link very delicately highlights all the filters that are there before DispatcherServlet and what is the importance of those Filters. Please refer the link below:
How Spring Security Filter Chain works
Now, we need to understand what authentication and authorization is:
Authentication- Anyone using your application needs to have some info and you need to verify that user’s username, password to allow him to access your application. If his username or password is wrong, that means he is not authenticated.
Authorization- Once the user is authenticated, there might be some URLs of your application that should only be allowed to admin users and not normal users. This is called authorizing a user to access some parts of your application based on his role.
Let us look at some important Spring’s Filter in Filter Chain:
• BasicAuthenticationFilter: Tries to find a Basic Auth HTTP Header on the request and if found, tries to authenticate the user with the header’s username and password.
• UsernamePasswordAuthenticationFilter: Tries to find a username/password request parameter/POST body and if found, tries to authenticate the user with those values.
• DefaultLoginPageGeneratingFilter: Generates a login page for you, if you don’t explicitly disable that feature. THIS filter is why you get a default login page when enabling Spring Security.
• DefaultLogoutPageGeneratingFilter: Generates a logout page for you, if you don’t explicitly disable that feature.
• FilterSecurityInterceptor: Does your authorization.
These filters, by default, are providing you a login page which you saw on your browser. Also, they provide a logout page, ability to login with Basic Auth or Form Logins, as well as protecting against CSRF attacks.
Remember, the login page at the beginning just after adding Spring Security to your pom.xml. That is happening because of the below class:
public abstract class WebSecurityConfigurerAdapter implements
WebSecurityConfigurer<WebSecurity> {
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
}
}
This WebSecurityConfigurerAdapter class is what we extend and we override its configure method. As per above, all the requests need to do basic authentication via form login method. This login page is the default provided by Spring that we saw when we accessed our URL.
Now, next question arises, what if we want to do this configuration ourselves? The below topic discusses exactly that:
How to configure Spring Security?
To configure Spring Security, we need to have a #Configuration, #EnableWebSecurity class which extends WebSecurityConfigurerAdapter class.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.httpBasic();
}
}
You must do above the mentioned configurations. Now, you can do your specific security configuration i.e. which all URLs are allowed, which need to be authenticated, what are the types of authentication the application will perform and what are the roles that are allowed on specific URLs.
So, basically, all your authentication and authorization information is configured here. Other configuration regarding CORS, CSRF and other exploits is also done here, but that is out of the scope of the basics.
In the example above, all requests going to / and /home are allowed to any user i.e. anyone can access them and get response but the other requests need to be authenticated. Also, we have allowed form login i.e. when any request apart from / and /home is accessed, the user will be presented with a login page where he will input his username and password and that username/password will be authenticated using basic authentication i.e. sending in an HTTP Basic Auth Header to authenticate.
Till now, we have added Spring Security, protected our URLs, configured Spring Security. But, how will we check the username and password to be authenticated? The below discusses this:
You need to specify some #Beans to get Spring Security working. Why some beans are needed?
Because Spring Container needs these beans to implement security under the hood.
You need to provide these two beans – UserDetailsService & PasswordEncoder.
UserDetailsService – This is responsible for providing your user to the Spring container. The user can be present either in your DB, memory, anywhere. Ex: It can be stored in User table with username, password, roles and other columns.
#Bean
public UserDetailsService userDetailsService() {
return new MyUserDetailsService();
}
Above, we are providing our custom MyUserDetailsService which has to be a UserDetailsService child for Spring container to identify its purpose. Below is the sample implementation:
public class MyDatabaseUserDetailsService implements UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Load the user from the users table by username. If not found, throw UsernameNotFoundException.
// Convert/wrap the user to a UserDetails object and return it.
return someUserDetails;
}
}
public interface UserDetails extends Serializable {
String getUsername();
String getPassword();
// isAccountNonExpired,isAccountNonLocked,
// isCredentialsNonExpired,isEnabled
}
You see, UserDetailsService shall provide the container with UserDetails object.
By default, Spring provides these implementations of UserDetailsService:
1. JdbcUserDetailsManager- which is a JDBC based UserDetailsService. You can configure it to match your user table/column structure.
2. InMemoryUserDetailsManager- which keeps all userdetails in memory. This is generally used for testing purposes.
3. org.springframework.security.core.userdetail.User– This is what is used mostly in custom applications. You can extend this User class on your custom implementation for your user object.
Now, as per above if any request arrives and needs to be authenticated, then since we have UserDetailsService in place, we will get the user from the UserDetails object returned by UserDetailsService for the user who has sent the request and can authenticate his sent username/password with the one received from our UserDetailsService.
This way, the user is authenticated.
Note: The password received from user is automatically hashed. So, if we do not have the hash representation of password from our UserDetailsService, it will fail even when the password is correct.
To prevent this, we provide PasswordEncoder bean to our container which will apply the hashing algorithm specified by the PasswordEncoder on the password in UserDetails object and make a hash for it. Then, it checks both the hashed passwords and authenticates or fails a user.
PasswordEncoder- This provides a hash of your password for security purposes. Why? You cannot/should not deal with plain passwords. That beats the very purpose of Spring Security. Better, hash it with any algorithm.
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
Now, you can autowire this PasswordEncoder anywhere in your application.
AuthenticationProvider-
In some cases, we do not have access to the user’s password but some other third party stores our user's information in some fancy way.
In those cases, we need to provide AuthenticationProvider beans to our Spring container. Once container has this object, it will try to authenticate with the implementation we have provided to authenticate with that third party which will give us a UserDetails object or any other object from which we can obtain our UserDetails object.
Once, this is obtained, that means we are authenticated and we will send back a UsernamePasswordAuthenticationToken with our username, password and authorities/roles. If it is not obtained, we can throw an exception.
#Bean
public AuthenticationProvider authenticationProvider() {
return new MyAuthenticationProvider();
}
An AuthenticationProvider consists primarily of one method and a basic implementation could look like this:
public class MyAuthenticationProvider implements AuthenticationProvider {
Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String username = authentication.getPrincipal().toString();
String password = authentication.getCredentials().toString();
User user = callThirdPartyService(username, password);
if (user == null) {
throw new AuthenticationException("Incorrect username/password");
}
return new UserNamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
}
}
Thats all there is to Spring Security basics or under the hood functionality and how we can leverage these to customize our security implementation. You can find examples anywhere. More advanced topics such as JWT, Oauth2 implementation, CSRF prevention, CORS allowance are beyond the scope.

Spring Security filters for JWT-based authentication, verification and authorization scheme, by example

Java + Spring (and Spring Security) here, interested in implementing a JWT-based auth mechanism for my web service using bearer tokens. My understanding of the proper way of using Spring Security for authentication and authorization is through the use of provided (or custom) filters as follows:
you specify which URLs in your app are authenticated (and thus require authenticated requests to access)
this is typically done in an #EnableWebSecurity-annotated web security class that extends WebSecurityConfigurerAdapter
for any unauthenticated URLs, no filters should block access to the resources being requested
an authentication filter effectively provides a "sign in" endpoint
request clients should hit this signin endpoint (authn filter) initially to obtain an auth token that can be used for making subsequent API calls
this filter should receive a type of "sign in request" object that contains a principal (e.g. username) and credential (e.g. password)
this authn filter should use the principal/credential contained in the sign in request to determine if they represents a valid user in the system
if so, an auth token (JWT, etc.) is generated and sent back to the requesters in the response somehow
else, if the principal/credential don't match a valid user in the system, an error response is returned and authentication fails
for authenticated URLs, a verification filter verifies that the request contains an auth token and that the auth token is valid (was signed correctly, contains user information such as JWT claims, is not expired, etc.)
if the auth token is valid, the request continues on to the authorization filter (see below)
else if the auth token is not valid, verification fails and the filter sends an error response back to the client
finally, an authorization filter verifies that the user associated with the valid auth token has the ability/permission to make such a request
if they do, then the request is allowed to continue on to whatever resources/controller was written to handle it, and that resource/controller provides the response back to the requester
if they don't, an error response is returned to the client
ideally the logic (code) inside this authz filter would have access to the permission annotations added to the resource method, so that I can add endpoints and specify permissions on them without having to modify the code of the authz filter
So to begin with, if anything I have stated above is a Spring Security (or web security in general) anti-pattern or is misled, please begin by providing course correction and steering me in the right direction!
Assuming I'm more or less understanding the "auth flow" above correctly...
Are there any specific Spring Security filters that take care of all of this for me already, or that can be extended and have a few methods overridden to behave this way? Or anything that comes really close? Looking at the list of authentication-specific Spring Security filters I see:
UsernamePasswordAuthenticationFilter -> looks like a decent candidate for the authn filter but expects a username and password parameter on the query string which is strange to me, and most importantly, does not generate a JWT
CasAuthenticationFilter -> looks like its used for CAS-based SSO and is not appropriate for use in non-SSO contexts
BasicAuthenticationFilter -> for HTTP basic authentication-based auth, not appropriate for more sophisticated setups
As for token verification and authorization, I (much to my surprise) don't see anything in the Spring Security landscape that could qualify.
Unless anyone knows of JWT-specific filters that I can use or subclass easily, I think I need to implement my own custom filters, in which case I'm wondering how to conigure Spring Security to use them and not use any of these other authentication filters (such as UsernamePasswordAuthenticationFilter) as part of the filter chain.
As I understand it, you want to:
Authenticate users via a username and password and respond with a JWT
On subsequent requests, authenticate users using that JWT
username/password -> JWT isn't an established authentication mechanism on its own, which is why Spring Security doesn't yet have direct support.
You can get it on your own pretty easily, though.
First, create a /token endpoint that produces a JWT:
#RestController
public class TokenController {
#Value("${jwt.private.key}")
RSAPrivateKey key;
#PostMapping("/token")
public String token(Authentication authentication) {
Instant now = Instant.now();
long expiry = 36000L;
// #formatter:off
String scope = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
JWTClaimsSet claims = new JWTClaimsSet.Builder()
.issuer("self")
.issueTime(new Date(now.toEpochMilli()))
.expirationTime(new Date(now.plusSeconds(expiry).toEpochMilli()))
.subject(authentication.getName())
.claim("scope", scope)
.build();
// #formatter:on
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
SignedJWT jwt = new SignedJWT(header, claims);
return sign(jwt).serialize();
}
SignedJWT sign(SignedJWT jwt) {
try {
jwt.sign(new RSASSASigner(this.key));
return jwt;
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
}
Second, configure Spring Security to allow HTTP Basic (for the /token endpoint) and JWT (for the rest):
#Configuration
public class RestConfig extends WebSecurityConfigurerAdapter {
#Value("${jwt.public.key}")
RSAPublicKey key;
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
.csrf((csrf) -> csrf.ignoringAntMatchers("/token"))
.httpBasic(Customizer.withDefaults())
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.sessionManagement((session) -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling((exceptions) -> exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
);
// #formatter:on
}
#Bean
UserDetailsService users() {
// #formatter:off
return new InMemoryUserDetailsManager(
User.withUsername("user")
.password("{noop}password")
.authorities("app")
.build());
// #formatter:on
}
#Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(this.key).build();
}
}
I think there's appetite to add support for something like this in spring-authorization-server to reduce the /token boilerplate, if you're interested in contributing your efforts!

Does Spring security JDBC authentication hit the Data base on every request

I wrote one program using spring security framework and used JDBC approach using DataSource. Following is piece of code.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/users/**").hasRole("USER")
.antMatchers(HttpMethod.POST, "/users/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/users/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/users/**").hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
.and().httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
}
This program is using default table what spring framework expect.
Now my question, because here I am using httpBasic authentication approach when I will come GET /users url, does spring framework hit the table on every request and valid user with credential or after first authentication it cache and validate against that cache.
Could someone help me to understand it.
Thanks in advance
If you use stateless HTTP Basic, the database will by default be "hit" on every request. If you find that a problem you can set a cache like this:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).userCache(userCache);
}
See UserCache javadoc for details about which cache implementations you can use.
Because you're using httpBasic(), then the query would be performed each time - this is the nature of stateless authentication, which is what folks using httpBasic() are typically driving at.
You could cache the JDBC query results with an L2 cache or similar.
Or, if you are okay with some authentication state, then you could
add session management, as another answer indicates. Doing this means that the first request would include credentials in the Authorization header and its response would include a session cookie. Subsequent requests would send that session cookie back, instead of the Authorization header, until the session expires.
use a token (like an OAuth token). You can instead present your credentials to an Authorization Server. The Authorization Server will exchange this for a token that you can then supply to the Authorization header (Authorization: Bearer) instead of the user's credentials (Authorization: Basic).
This behaviour is configured by sessionManagement().sessionCreationPolicy() when configuring HttpSecurity.
Unless you set it to sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) ,its default value is IF_REQUIRED which will cache the authentication result (i.e. SecurityContext) in the HttpSession.Subsequent requests from the same session will simply get the authentication result from the session rather than hitting the database to validate the credential .

Is it necessary to protect JAX-RS requests against CSRF?

Is it necessary to protect JAX-RS requests against CSRF?
By definition REST is stateless and therefore exists no session id (session cookie), because there is no session at all (see also https://stackoverflow.com/a/15746639/5277820).
My Spring Security Java Configuration:
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Configuration
#Order(1)
public static class JaxRsWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.antMatcher("/services/**")
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/services/**").permitAll()
.anyRequest().hasAuthority("ROLE_user")
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
}
}
But I found for example following blog: Stateless Spring Security Part 1: Stateless CSRF protection. Unfortunately the blog does not explain, why one needs CSRF protection.
Is there any other CSRF attack without session cookie?
CSRF attacks don't need a session to exist. A CSRF attack consists in doing something on a user's behalf by tricking him/her into clicking a link or submitting a form that goes to an application where the user is logged in.
Whether basic authentication or a session cookie is used to identify the user is irrelevant.
Note that using a cookie doesn't mean that the app is not stateless. A cookie, just like basic authentication, simply consists in sending an additional header with each HTTP request.
Access tokens are sometimes stored in a (secured http-only at best) cookie, so that clients don't have to bother adding it in each request manually: cookies are automatically attached to the requests by the browsers. This is a reason why CSRF protection needs to be implemented.
The article you linked proposes to have the clients generate and send the same unique secret value in both a Cookie and a custom HTTP header, which is quite smart:
Considering a website is only allowed to read/write a Cookie for its
own domain, only the real site can send the same value in both
headers.
That is, if you receive an email with a fake image targeting http://yourserver.com/admin/deleteAll for example (and the server handles it through GET...), the unique secret won't be set in the request header (an old one could still be present in a cookie): the server must reject the request.

Spring Security OAuth2 client_credentials flow only

I'm trying to use Spring Boot to create an OAuth2 authorization that only supports the client credentials flow. As I understand that flow, the client accesses the /oauth/token endpoint directly.
Is there a way to disable the /oauth/authorize endpoint in Spring Boot and allow direct access to /oauth/token without having to be fully authorized first?
#Configuration
#EnableAuthorizationServer
public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// TODO: Is there something I can do here to disable /oauth/authorize?
endpoints.authenticationManager(authenticationManager);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// client details configuration
}
}
I can't speak to disabling the authorize endpoint but you're right that you can go directly to the token endpoint with the client credentials flow. I'm probably restating something you already know but the credentials for a "client" (client_id/client_secret) are different from the credentials of a "user" (username/password). A "user" goes to the authorize endpoint so that the client can then get tokens from the token endpoint. A "client" (in the client credentials flow) provides the client credentials to the token endpoint directly. Do you need to disable the authorize endpoint?
So, for client_credentials flow, you don't need to go to authorize first (you don't need to disable it). Here's how you'd curl your token if your Spring Boot authorization server was on localhost:8080:
curl -H "Authorization: Basic d2VhcHA6" -X POST http://localhost:8080/oauth/token?grant_type=client_credentials
where d2VhcHA6 is the base64 encoding of your "client_id:client_secret"

Categories

Resources