- Spring security is a de facto Standard for securing spring based applications.
- Spring security provide the web level security.
- Screen security automate login, logout and password encryption with latest Techniques like bcrypt.
- Has to configure above features safely.
- Also provide us with authentication and authorisation
- Spring security provides us with role based authorisation.
- Before Spring 4 or Spring 5 We used spring boot security oAuth2 library.
- Now we use SpringSecurityOAuth2AutoConfigure
- Spring security is an application framework that helps you to do application level security
- Spring security includes the security And the configuration that needs to be done.
- Spring security provides following functionalities
- Login and logout functionality
- Allow/block access to URL to logged in users
- Allow/block access to URL to logged in user with certain roles.
- Handles common vulnerabilities like
- Session fixation
- Click Jacking
- Click Site request forgery
- Spring security is widely adopted in industry
- We can provide following types of authentication
- Username/password authentication
- SSO/Okta/LDAP
- App level authorisation
- IntraApp authorisation like OAuth
- Micro-services security(using tokens,JWT)
- Method level security
- Items related to spring security
- Authentication
- Authentication is based on password, pin code, answer to a secret/personal question is called as knowledge based authentication.
- Authentication based on phone/text messages, keywords and badges and access token device is called as Possession based authentication
- When we combine knowledge based authentication and possession based authentication, we get multi-factor authentication.
- We configure spring security authentication by changing the authentication manager behaviour.
- We use authentication Manager builder to change the default authentication manager functionality, or behaviour.
- We provide type of authentication like in memory authentication, et cetera, and provide username and password and role information in the overridden configure method of the WebsecurityconfigurerAdapter class.
- Authorisation
- Determines the access level of a person who has logged in. It may block a user if it is not allowed to perform a specific task.
- Determines if the user is allowed to perform a specific operation or not.
- Different API is have different authorisation requirements.
- We configure by changing the default behaviour of HTTP security in overridden configure method Which accepts Httpsecurity as parameter in class extending WebsecurityconfigurerAdapter.
- Use hasAnyRole() to specify Multiple roles.
- Use hasRole() 2 specify particular role.
- Use antMatchers to specify Matching URL’s
- We specify path using wild cards in http.authorizeRequests().antMatchers()
- “/**” matches all paths In current Level and any nested level below this.
- We go from Most restrictive URL to least restrictive URL from top to bottom.
- Keep admin roles at top
- Example course-api
- Principle
- A person we have identified through the process of authentication is called as principal.
- A principal is currently logged in user.
- Are user may have multiple accounts. The particular account used to login at a time is called as principal.
- GrantedAuthority
- The user can only perform an action only if he has been granted authority to do so.
- Authorities are fine, grain permissions Of what user can do.
- Role
- A role Is a group of authorities. Rolls are used when similar group of authorities have been assigned to multiple users. So instead of assigning them an authority individually, we assigned them a role.
- Roles are more course grain going permissions
- Spring uses spring – boot – starter – security dependency to enable security
- Spring security uses filters to implement a security. Filters are used to modify the headers of a Request before it reaches the spring.
- Filters are the crosscutting concerns.
- Filters can be applied to one or more URL
- A filter is a construct in a servlet application That helps to intercept requests Before it goes to servlet.
- A filter can manipulate request before it goes to the servlet.
- A filter can even stop a request from reaching servlet.
- Spring security adds mandatory authentication after all URL, except following URL
- “/error”
- Add login form
- “/login”
- Handles any login errors.
- Spring security does the filter mapping by intercepting all the request and mapping them to spring security own Filter called as delegating filter proxy.
- Spring security, adds the delegating filter, proxy, or default filter, which catches all URL.
- Spring security adds its own filter that is org.springframework.DelegatingFilterProxy.
- This filter delegates the job to a bunch of other spring security specific filters to different things like URL authorisation or security configuration.
- The above delegation depends on URL being requested or configuration we have going on for spring security, App.
- Even if there is no configuration, there are 5-6 Filters that spring security runs through.
- For example, the Authentication filter, intercept all of these authentication request and initiate the authorisation process.
- When the authentication is successful, it returns the principal That is information about the logged in user.
- Authentication is an interface in spring security, which holds credentials before authentication and principal if the Authentication succeeds.
- The implementation of authentication provider performs the authentication. It is an interface with method, authenticate.
- Authentication provider provides the mechanism with which authentication should happen.
- The authentication provider is a common way to implement authentication manager.
- The authentication Manager uses provider pattern To delegate to concerned authentication provider.
- It delegates to authentication provider depending on Which ever provider supports the Authentication mechanism provided.
- It checks for all the providers which support the authentication type and delegate to the necessary authentication provider.
- The authentication Manager supports authenticate And supports method. The authenticate method does authentication and supports method tells which authentication type it supports.
- Another filter is for authorisation, which skips authorisation of static resources like JS files, CSS files, et cetera.
- Spring security has a user details, service, which defines how, and from where we will retrieve the user information.
- This service takes in a username and returns the object of user, details.
- All the user information is in the user details object which is used by the authentication provider post authentication To be set as principal.
- Authentication Manager uses support method to check if it supports the requested authentication type.
- The authentication object goes back to the authentication filter.
- If user is not authenticated, then authentication provider through Unauthenticated exception, which is accordingly handled by filter else it returns the Principal which is the UserDetails object.
- All the user information that is, it is valid or locked or unlocked is in the user details, object that the user detail service returns using loadUserByUserName() method.
- Once the authentication provider authenticates the UserDetails objects It returns it as the principal.
- We use key identity to store and get user information corresponding to the username provided
- User details, service takes in a username and loads user Using loadUserByUsername() method.
- Hence, the steps for authentication are as follows
- The authentication filter intercepts the authentication request, it creates the authentication object with credentials and passes it to the authentication Manager.
- The authentication Manager, then find the appropriate authentication provider using supports method.
- The authentication manager calls the authenticate method on the concerned provider and passes the authentication object
- The authentication provider looks up the corresponding user in the system by using the user details, service.
- User details service Returns the user, details instance, which the authentication provider then verifies And authentication happens.
- If the authentication is successful, the authentication object is returned back with the principal and authorities filled in.
- The authentication object is sent back to authenticate filter that started it off.
- If the authentication is not valid, then the authentication provider through the unauthorised exception.
- This exception bubbles, all the way up to the filter, which is caught or shown as per the handle provided.
- The authentication filter on getting the authentication object, saves it in the thread context
- The authorisation object which is authenticated is put in the security context of the local thread object.
- This context is called as security context of the thread.
- It can be used in authentication, for use in identifying current principal, et cetera.
- This context is linked to the current user session using another filter
- Thus we authenticate Only once, and we can access the application for the duration of that session.
- The filter, then, for every request, takes the object for session and saves to thread local again.
- Creates a user and set a default password
- Default username is user, which can be changed from spring.security.user.name property
- Default password is randomly generated and is shown in console when we run the application. This can also be overridden Using property spring.security.user.password
- Now we can even create a bean of type Securityfilterchain To configure security as websecurityconfigureradapter, class has been deprecated.
- Password should be hashed before saving
- Create a bean of type PasswordEncoder And spring will automatically use it for password encoding.
Configure Spring Security
- When we configure security following is the sequence of files which are checked.
- AppScurityConfig extends WebSecurityConfigurerAdapter
- We override configurer method
- authProvider method gets user details from UserDetailsService.
- https://github.com/gauravmatta/springmvc/blob/master/course-api/src/main/java/com/springimplant/cms/config/AppSecurityConfig.java
- MyUserDetailsService implements UserDetailsService
- Loads user info and sets it to UserDetails instance using loadUserByUserName() method.
- https://github.com/gauravmatta/springmvc/blob/master/course-api/src/main/java/com/springimplant/cms/service/MyUserDetailsService.java
- UserPrincipal implements UserDetails gets User information based from our storage.
- UserPrincipal is returned by UserDetailsService
- https://github.com/gauravmatta/springmvc/blob/master/course-api/src/main/java/com/springimplant/cms/entities/UserPrincipal.java
Spring Security Password Encoding
- Different encryption ways to secure password are as follows
- Cipher text
- It is not safe as it is easy to decrypt using keys and Has been broken down.
- Hashes
- SHA
- Output length of encrypted password is always same.
- Message Digest 5(MD5)
- Very old and has been broken down.
- SHA 256/ SHA 512
- Hackers are able to crack And create collision codes.
- We have multiple computation and calculation going on at same time, which makes process slow.
- Bcrypt
- Hashes, the password in multiple rounds.
- Based on Blowfish Cipher
- Calculate the hash and times based on the number specified.
- We set the Password Encoder property of the DaoAuthenticationProvider.
- Setting it to NoOpPasswordEncoder.getInstance() makes us use plain passwords.
- Set passwordEncoder property of DaoAuthenticationProvider to new instance of BCryptPasswordEncoder();
Access control using Redis
- SecuringMicro-services with API based Authentication – spring cloud gateway.
- All requests are routed to Spring cloud gateway.
- API gateway routes request to concerned micro services based on routes defined in the redis cache.
- We can have a separate authentication micro service to update keys in redis cache.
- Code Example
Spring Security Filters Chain
- When a client sends request to servlet. It goes through a sequence of the filters.
- Spring web framework provides a special filter framework called as “filter chain proxy”.
- We can configure set of internal filters using filter, chain proxy, depending on the application, security configuration.
- Each filter applies a specific security concern to the current request.
- For example. We can insert our custom filter like JWT token filter here in this filter set to provide JWT security.
- This filter checks for the availability and verifies the integrity of the access token in the request.
- If the token is verified, then the request is passed through the downstream filters and finally reaching the destination Servlet.
Spring Security and JWT to secure Web services
- JWT stands for Json web Token.
- JWT is used to perform User authorisation In web applications.
- JWT Creates a standard way for two parties to communicate securely.
- It uses open industry, standard specification, RFC 7519 Which outlines how JWT must be structured and how it should be used for exchanging information.
- JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a Json object.
- The client passes JWT with every request and server identifies or authorises the client based on JWT passed.
- JWT is a value token as it contains the information within it.
- JWT is compact.
- A JWT string can be easily used in HTTP authorization headers and URI query parameters.
- JWT is trustworthy
- A JWT is digitally signed using a secret key or a public/private RSA key pair.
- Tokens can be verified and cannot be tampered with.
- Follows stateless authentication mechanism.
- User input and state is not stored in server memory or cookies.
- In traditional systems we used to pass username and password in each request.
- To overcome this, we use JWT via Vitas user name and password as part of our first request and application returns a Json token.
- This token is then used to validate each request.
- Jason token is an encrypted string of our user name and password.
- A JWT is a string representing a set of claims as a Json object.
- A claim is a piece of information asserted about a subject, represented as a name/value pair(claim name/claim value)
- JWT consist of three parts separated by dot
- Header
- The first part specifies the header,which defines which algorithm we are going to use, and the type of the token.
- Defines the type of Algorithm used in encoding, for example, like HS 256 et cetera.
- This is encoded using base 64.
- Payload
- The second part defines our payload data i.e user details.
- The data that we want to send and is encoded using base 64
- Signature
- Third part specifies a verify signature-so our header and payload is converted to base 64 URL encoder, and it will give you verify signature.
- It is used by server to sign the JWT token.
- Signature is created using the same algorithm as in header.
- It is signed using the information in payload and header.
- An example of JWT token can be found on https://jwt.io/
- In the first request we send user name and password and we get an access token as a response.
- Then we use that access token to authenticate for other endpoints.
- Client can store JWT either in local storage or in a cookie. It has to send a token in every subsequent request after the first authentication request where it has received the token.
- Client passes JWT in HTTP header using key “Authorisation” and value “Bearer JWT Token”.
- The server examines the request Checks for JWT token and generates its signature using header and pay load. If it matches the signature sent by client, it is considered as trusted Else, JWT is considered as tampered.
- Other authorisation strategies used prior to JWT are Session Token.
- Session token is a reference token It contains reference to the session information.
- Challenges with JWT
- JWT is readable, thus secure information like PII or confidential/sensitive information cannot be sent along JWT.
- Someone can steal JWT and impersonate it on behalf of themselves as server just verifies Authenticity of JWT.
- We should only transmit over HTTPS connection and it has to be in conjunction with other established authorisation mechanisms like OAuth etc.
- JWT’s can’t be disabled, however, they can be expired or blacklisted.
- Code Example : springmvc/spring-security-jwt at master · gauravmatta/springmvc (github.com)
JWT- Role Based – Authorization
- Implement role based authorization for rest API’s with JWT in spring boot application.
- Add roles(authorities) to users.
- Store user’s authorities in JWT.
- Parse user’s authorities from JWT.
- Add Authorization to REST API’s using @RolesAllowed annotation.
- Test JWT role-based authorization using postman.
- Code
- OAuth is meant for authorisation and not authentication.
- OAuth Was meant to authorise a service from another service.
- For example If our application wants to access the resource of another user on a cloud like photos on Google, et cetera.
- OAuth was a standard created where a service could authorise another service on behalf of a user.
- Currently OAuth 2.0 Is being used.
- In OAuth a limited access key Is given to a service who wants to access certain information from an account.
- The token used by OAuth Is also JWT token.
- OAuth is used to authorize via third party Authorization Services such as Google,Github etc.
- OAuth 2.0 Is an authorisation framework that enables applications to obtain limited access to user accounts on HTTP service such as FACEBOOK,GitHub, And digital ocean.
- We have a client ID and secret ID and oauth, server URL.
- Valid the token,Authorisation token, if the token has expired, then we can refresh the token.
- Access token is automatically generated after a limited time like 15 mins etc.
- Key Terminologies
- Resource/Protected Resource
- Resource is an entity sought by actors in OAuth space.
- Resource Owner
- A person who has access to the resource at present.
- An entity capable of joining access to a protected resource
- Resource Server
- It is the server that is holding the protected resource.
- The resource server/holder is responsible for the security of the resource.
- Client
- The client is the application which needs access to the protected resource.
- An application making protected resource request on behalf of the resource owner with its authorisation.
- Authorisation server
- The resource server is coupled with an authorisation server.
- The server Issuing access tokens to the client is called as authorisation server.
- The authorisation server is responsible for making sure Whoever is accessing the resource is authorised.
- The resource server implement authorisation server Which provides the service of OAuth.
- The authorisation server may be a separate server, or it may be Integrated with Resource Server.
- OAuth Flows
- Authorisation code flow
- User logs into client and ask client to access resource server.
- The client talks to authorisation server regarding resource access.
- The authorisation server goes to resource owner for access confirmation to the services/permissions requested by client.
- The resource owner Approve the access on authorisation server.
- The authorisation server on approval sends an authorisation token to the client.
- The client uses the authorisation token to get the access token from the authorisation server.
- The authorisation server provides an access token which can be used to contact resource server and get access to the resource.
- The resource server validate the token and provides access to the resource.
- Implicit flow
- The resource owner asks client for access to resource on resource server.
- The client connects with authorisation server of the resource server.
- Authorisation server goes to resource owner for approval.
- The resource owner approves the access.
- The authorisation server directly provides the access token with no Authorisation token involved.
- The client makes a call to the resource server With the access token to access the resources.
- The resource server validate the excess token and provides access to the resource.
- Any other service, which gains access to this access token Can impersonate the service and misuse token. This is a drawback of this method.
- Since this flow is not as secure as authorisation code flow, it is used primarily for very short-lived, access tokens, used for JavaScript applications, et cetera.
- The micro service use case flow
- OAuth is basically used for authorisation between micro services.
- Micro service 1 calls authentication server for micro service 2 access.
- The authentication server gives an access token to micro service 1 For access to required information.
- Micro service 1 calls micro service 2 With access token for required information.
- Micro service 2 Validate token and allows access to the required information.
- The client credentials flow
- Used when client is well trusted (Confidential clients)
- Disadvantages of OAuth
- If the client is not well known, then the resource owner may not provide authentication for resource server And thus his-information.
- If the access token is lost Then someone else will impersonate user.
- If the user has logged out of resource server Account, then the client may not be able to access resource next time.
- Each time the application is using OAuth Token, the user must have a valid session in resource server.
- Add dependency to POM and configure the project as follows.
- Use the following as redirect urls while creating app in services
- http://localhost:8081/login/oauth2/code/google
- http://localhost:8081/login/oauth2/code/github
No comments:
Post a Comment