Skip to main content

Posts

Showing posts from April, 2016

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.SessionCreationPolicy;   import  org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;      /**    * @author e

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 : Implement Role Hierarchy with In-Memory Authentication

Implement Role Hierarchy with In-Memory Authentication In order to configure role hierarchy, you need to make a bean RoleHierarchy define a expressionhandler to read role hierarchy package com.ekiras.ss.config; import org.springframework.context.annotation.Bean; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; 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.web.FilterInvocation; import org.springframework.security.web.access.e

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