Skip to main content

Posts

Showing posts with the label Security

SpringSecurity : How to disable Session Creation for Stateless Authentication

How to disable Session Creation for Stateless Authentication We need to disable session creation for authenticating requests based on token based authentication. This can be easily configured by the following configurations. view plain copy to clipboard print ? package  com.ekiras.ss.security.config;      import  com.ekiras.ss.security.filter.TokenAuthenticationFilter;   import  org.springframework.context.annotation.Bean;   import  org.springframework.core.Ordered;   import  org.springframework.core.annotation.Order;   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.config.http.SessionC...

SpringSecurity : Authenticate User with Custom UserDetailsService

Points To Remember Create class that implement UserDetailsService and override loadUserByUsername() method. Throw UsernameNotFoundException if no user was found by username. Register this class as a bean by overriding WebSecurityConfigurerAdapter . Authenticate User with Custom UserDetailsService Step 1 : Create Entities for User and Role Create Entity User package com.ekiras.ss.domain; import javax.persistence.*; import java.util.Set; /** * @author ekiras */ @Entity public class User { @Id @GeneratedValue (strategy = GenerationType.AUTO) private long id; private String username; private String password; private boolean enabled; @ManyToMany (fetch = FetchType.EAGER,cascade = CascadeType.ALL) @JoinTable (joinColumns = @JoinColumn (name = "user_id" ),inverseJoinColumns = @JoinColumn (name = "role_id" )) private Set<role> roles; // GETTERS and SETTERS } Create Entity Role package com.ekiras.ss.domain; ...

SpringSecurity : Configure JDBC Authetication using MYSQL Query

Create Database Schema and tables First we will create a Database Schema as shown in the image below. We have to create 3 Tables in database. user - to hold the user data. role - to hold the data of roles that a user can have. user_roles - to hold the mapping of user and roles. Configure JDBC Authetication using MYSQL Query. Step 1 : Add the Dependencies compile('org.springframework.boot:spring-boot-starter-data-jpa') runtime('mysql:mysql-connector-java') Step 2 : Add the Datasource properties spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost/demo_ss spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.maxActive=10 spring.datasource.max-idle=4 spring.datasource.min-idle=2 spring.datasource.test-while-idle=true spring.datasource.test-on-borrow=true spring.datasource.validation-query=SELECT 1 spring.datasource.time-between-eviction-runs-millis=60000 ...

SpringSecurity : How to list the User Authorities in Controller,Filter and Services

How to get the User Authorities in Controller,Filter and Services You can get the user authorities from the SecurityContextHolder . getContext().getAuthenication().getAuthorities() will return the authorities for the currently logged in user. You cannot add the user Authority to this collection of user Authorities. public Object authorities () { Set<grantedauthority> authorities = (Set<grantedauthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); if (authorities.contains( "ADMIN" )){ // do something return "" ; } else if (authorities.contains( "USER" ) ) { // do something else return "" ; } else { // do something else return "" ; } } As shown in the example above you can get the user authorities by the following method. Collection authorities = SecurityContextHolder.getCo...

SpringSecurity : Configure In Memory Authentication

Configure Spring Security to Authenticate user using In-Memory Authentication. To implement inMemory authentication, all you need to do is extend WebSecurityConfigurerAdapter . override configure(AuthenticationManagerBuilder) method add username , password and roles/authorities for authentication. After adding the following class to your application, you will be able to login using these username password pairs. package com.ekiras.ss.config; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * @author ekiras */ @EnableWebSecurity public class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter { @Override protected void configure (AuthenticationManagerBuilder auth) throws Exception { auth...

SpringSecurity : How to configure Spring Security with Spring boot

How to integrate Spring Security with Spring boot Add the following dependency in your build.gradle compile('org.springframework.boot:spring-boot-starter-security') Basic Spring Security Configurations Add the dependency in your build.gradle Run your application gradle bootRun for gradle and mvn spring:run for maven The default username is user and the password will be printed in the logs as shown in the image above. So in this case you can login using username = user password = // printed in logs Note A new password will be created each time the application restarts. Spring Security Configurations with defined username and password Add the following in your application.properties security.user.name=user security.user.password=password security.user.role=USER, ADMIN Using this approach you will be able to login to your application using the username and password defined by you. The default Roles assigned on login will be the one specified by you in properties file. Also Read Co...

Spring Security : Getting started with Spring Security and Spring Boot

Points To Remember Add dependency of spring security Add custom username password in application.properties A unique password is generated each time application is started if no authentication process is specified. You can configure your own authentication  providers, managers, filters, entry points, tokens etc as required. Getting started with Spring Security and Spring Boot In order to apply Spring Security to a Spring Boot application, firstly you need to add the dependency in the application as follows In Maven you can do it as follows. <dependencies> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.0.3.RELEASE</version> </dependency> </dependencies> In Gradle you can do it as follows. dependencies { compile 'org.springframework.security:spring-security-web:4.0.3.RELEASE' } Your initial project may look like as s...

Spring Security : Custom UserDetailsService and Custom UserDetails

Points To Remember You need to change the UserDetailsService, User Object of the spring security to achieve this. Add Custom User Details to Spring Security Authentication Object First of all we nee to create a new User Object that will override the User class of the spring security in package  org.springframework.security.core.userdetails.User  After this, you need to tell  UserDetailsService to use this object as the principal for the authentication token. For this you will have to override the UserDetailsService of the spring security. You can have the custom User object like. Custom User Class -> MyUser.groovy package com.ekiras import org.springframework.security.core.GrantedAuthority /** * Created by ekansh on 24/1/15. */ class MyUser extends org.springframework.security.core.userdetails.User { // Declare all custom attributes here private final Object id; private String name; public MyUser(String username, String password, boolean enabled, bool...

Spring Security : Create a Custom Authentication Filter

Points To Remember You may need to create an AuthenticatioFilter when you want to create a custom logic for handling the authentication filter. You may also want to create your own Authentication Provider, Entry Point, Authentication Token etc to customize the authentication process to a new level. Step 1 : Create a Filter Let us first create a class named MyAuthenticationFilter and then register it as a bean in resources.groovy . After we have created the class and registered the it as a bean, we can use this class as a filter for our custom spring security authentication. Class : MyAuthenticationFilter.groovy package com.ekiras import org.springframework.context.ApplicationEventPublisher import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent import org.springframework.security.core.Authentication import org.springframework.security.core.AuthenticationExce...

How to integrate Spring Security in Grails

Points To Remember Go to the Grails Spring Security Plugin  and add the dependency in the BuildConfig . Integrate Spring Security in Grails Add the latest grails spring security plugin in the build config of the project. This will add spring security jars and classes that will be used to configure spring security in the project. http://grails.org/plugin/spring-security-core Now run the following command from the terminal. grails s2-quickstart com.ekiras User Role Here the syntax of the above command is grails s2-quickstart {package} {user domain} {authority domain} The above command will create three Domains in the project User, Role and UserRole. user domain will contain the user info, role domain will contain Authorities and UserRole will contain the user authority mappings. It will also add the following settings to the Config.groovy // Added by the Spring Security Core plugin: grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.ekiras.User' grails.plugin.spri...

Test CAS Rest API from Java Code

Points To Remember Make sure that your CAS Server is up and running. How to set up CAS Rest api with JDBC Authentication. You have created a database and have dummy data in it. Program : Test CAS Rest Api from a Java Code You can use the following piece of code to test the CAS Rest API. You need to follow the following points for Authentication a user on CAS You need to make a GET or POST call depending on your CAS server setup. If the Username and Password are correct then you will get a TGT (Ticket Granting Token) Now we will make a call to the service url of our application to get the Service Ticket. On success you will get a Service Ticket If you have service the Service Token,  then you have successfully authenticated the user. Save this service ticket in a cookie or session, since a service ticket can be used only once You will get the following type of response if everything is working fine. string s = username=admin%40gmail.com&password=igdefault 201 https://ekansh:84...