Here is my security-context.xml file:
<http auto-config='false' authentication-manager-ref="authenticationManager" entry-point-ref="authenticationEntryPoint">
<intercept-url pattern="/"/>
<intercept-url pattern="/**"/>
<csrf disabled="true"/>
<custom-filter position="REMEMBER_ME_FILTER" ref="DashboardFilter"></custom-filter>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="DashboardAuthProvider"></authentication-provider>
</authentication-manager>
<beans:bean id="DashboardFilter" class="com.apple.store.dashboard.security.DashboardAuthFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
</beans:bean>
<beans:bean id="authenticationEntryPoint" class="com.apple.store.dashboard.security.DashboardAuthEntryPoint">
</beans:bean>
<beans:bean id="DashboardAuthProvider" class="com.apple.store.dashboard.security.DashboardAuthProvider">
I have defined DashboardAuthProvider as such:
public class DashboardAuthProvider implements AuthenticationProvider {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthProvider.class);
#Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
logger.debug("Inside DashboardAuthProvider: authenticate method +authentication=" + authentication);
Authentication auth = null;
[...]
}
}
When I executed the code, I can hit the filter, but not provider. I read many spring security related document and couldn't find anything wrong with my configuration in xml. Could someone help?
Here is my filter:
public class DashboardAuthFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthFilter.class);
public DashboardAuthFilter() {
super("/**");
}
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
throws org.springframework.security.core.AuthenticationException {
logger.debug("Inside DashboardAuthFilter:attemptAuthentication method:");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth!=null ){
if (auth.isAuthenticated()){
logger.debug("Previously authenticated.isAuthenticated=true::: Auth details:" +auth);
return auth;
}
}
//Validate the DS Auth Cookie
Cookie AOSCookie = WebUtils.getCookie(request, "myacinfo-uat");//
if ( AOSCookie == null )
return null;
Authentication authResult = null;
try {
if( org.apache.commons.lang.StringUtils.isEmpty(AOSCookie.toString())) {
throw new PreAuthenticatedCredentialsNotFoundException("DS Auth Cookie not found. Commence DS Authentication..");
}
String credentials = "NA";
String validateCookieDetails = correctAuthentication(AOSCookie, request);
logger.debug("validateCookieDetails ....." + validateCookieDetails);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(validateCookieDetails, credentials);
authResult = getAuthenticationManager().authenticate(authRequest);
logger.debug("Attempted authentication: authResult ::" + authResult.toString());
} catch (org.springframework.security.core.AuthenticationException e) {
logger.error("AttemptAuthentication: Not Authenticated : AuthenticationException ....." + e.getMessage());
} catch (Exception e) {
logger.error("Exception occured during authentication....." + e.getMessage());
}
return authResult;
}
}
Related
Tried various ways to get custom message from spring, if user authentication fails.
Using
<spring.version>4.2.4.RELEASE</spring.version>
<spring.security.version>4.0.3.RELEASE</spring.security.version>
XML configuration
<http auto-config="true" use-expressions="false">
<intercept-url pattern="/**" access='ROLE_FUNCTION' />
<form-login login-page="/login"
default-target-url="/welcome"
username-parameter="j_username"
password-parameter="j_password"
login-processing-url="/j_spring_security_check"
always-use-default-target="true"
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-handler-ref="authenticationFailureHandler"
/>
<logout logout-url="/j_spring_security_logout" logout-success-url="/login?logout" delete-cookies="JSESSIONID" />
<access-denied-handler error-page="/accessDenied" />
<csrf disabled="true"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="**userDetailsService**">
<password-encoder ref="bcryptEncoder"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="authenticationSuccessHandler" class="com.company.project.CustomAuthenticationSuccessHandler"/>
<beans:bean id="**authenticationFailureHandler**" class="com.company.project.CustomAuthenticationFailureHandler"/>
<beans:bean name="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
Bean definition excerpt is as below
Implementation
userDetailsService
#Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.info("Getting access details for user : {}", username);
UserDto userDto = null;
boolean accountNonExpired = true;
boolean accountNonLocked = true;
boolean credentialsNonExpired = true;
boolean enabled = true;
try {
userDto = userService.loginUser(username);
if (userDto == null) {
throw new UsernameNotFoundException("User not found");
}
if (Active.Y != userDto.getActive()) {
enabled = false;
throw new BadCredentialsException("User account is inactive");
}
} catch (BaseException be) {
throw new BadCredentialsException(be.getMessage().toLowerCase());
}
UserContext context = new UserContext();
context.setLoginId(username);
context.setName(userDto.getName());
context.setPrincipleId(userDto.getId());
List<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(userDto);
String password = getActivePassword(userDto);
accountNonExpired = isAccountActive(userDto);
accountNonLocked = isAccountUnlocked(userDto);
credentialsNonExpired = isCredentialsActive(userDto);
return new UserLoginDetails(grantedAuthorities, password, username, accountNonExpired, accountNonLocked, credentialsNonExpired, enabled, context);
}
}
authenticationSuccessHandler works fine.
authenticationFailureHandler
#Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Autowired
UserService userService;
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
try {
// execute it when user enters wrong password, i.e loginAttempt ...
} catch (Exception e) {
// TODO: something
}
// TODO: how do I send message, if authenticationException.
redirectStrategy.sendRedirect(request, response, "/login?error");
// clearAuthenticationAttributes(request);
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
To show error message I'm using following line
JSP
<c:set var="errorMessage" value="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message}" />
Let me brief the expected messages.
If user enters wrong credentials he should get
"Invalid credentials"
If user account is inactive he should get
"Your account is not active"
If user exceeded permissible no. of
attempt his account will get locked and he will get "Your account is
locked"
If my implementation is not correct please let me know what changes should be done.
If you want to override the AuthenticationFailureHandler, you can extend the SimpleUrlAuthenticationFailureHandler, it already has a method to save exception.
protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
if (forwardToDestination) {
request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
} else {
HttpSession session = request.getSession(false);
if (session != null || allowSessionCreation) {
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
}
}
}
When you save the exception to request or session, then you can get the message.
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
I setup spring security for my rest apis. Here is a sample of my rest call,
GET: http://localhost:8081/dashboard/epic/data. When executing, filter, provider and eventual onAuthenticationSuccess are triggered. Here is the problem, instead of executing the rest url after authentication, it will go back to filter many times. For the second time, request.getRequestUrl will be http://localhost:8081/dashboard.
Here is my security-context.xml:
<http auto-config='false' authentication-manager-ref="authenticationManager" entry-point-ref="authenticationEntryPoint">
<intercept-url pattern="dashboard/**" access="ROLE_USER" />
<csrf disabled="true"/>
<custom-filter position="REMEMBER_ME_FILTER" ref="DashboardFilter"></custom-filter>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="DashboardAuthProvider"></authentication-provider>
</authentication-manager>
<beans:bean id="DashboardFilter" class="com.apple.store.dashboard.security.DashboardAuthFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="authenticationSuccessHandler">
<beans:bean class="com.apple.store.dashboard.security.LoginSuccessHandler">
</beans:bean>
</beans:property>
</beans:bean>
<beans:bean id="authenticationEntryPoint" class="com.apple.store.dashboard.security.DashboardAuthEntryPoint">
</beans:bean>
<beans:bean id="DashboardAuthProvider" class="com.apple.store.dashboard.security.DashboardAuthProvider"> </beans:bean>
Here is my filter
public class DashboardAuthFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthFilter.class);
public DashboardAuthFilter() {
//super("/j_spring_cas_security_check");
super("/**");
}
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
throws org.springframework.security.core.AuthenticationException, UnsupportedEncodingException {
logger.debug("Inside DashboardAuthFilter:attemptAuthentication method:");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth!=null ){
if (auth.isAuthenticated()){
logger.debug("Previously authenticated.isAuthenticated=true::: Auth details:" +auth);
return auth;
}
}
String _username = null;
String _password = null;
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
StringTokenizer st = new StringTokenizer(authHeader);
if (st.hasMoreTokens()) {
String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
logger.debug("Credentials: " + credentials);
int p = credentials.indexOf(":");
if (p != -1) {
_username = credentials.substring(0, p).trim();
_password = credentials.substring(p + 1).trim();
}
} catch (Exception e) {
}
}
}
}
else
System.out.println("request url is "+request.getRequestURL());
Authentication authResult = null;
try {
if( org.apache.commons.lang.StringUtils.isEmpty(_password)) {
throw new PreAuthenticatedCredentialsNotFoundException("No username:password..");
}
String credentials = "NA";
//String validateCookieDetails = correctAuthentication(AOSCookie, request);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(_username+":"+_password, credentials);
authResult = getAuthenticationManager().authenticate(authRequest);
logger.debug("Attempted authentication: authResult ::" + authResult.toString());
} catch (org.springframework.security.core.AuthenticationException e) {
logger.error("AttemptAuthentication: Not Authenticated : AuthenticationException ....." + e.getMessage());
} catch (Exception e) {
logger.error("Exception occured during authentication....." + e.getMessage());
}
return authResult;
}
Here is my provider:
public class DashboardAuthProvider implements AuthenticationProvider {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthProvider.class);
#Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
logger.debug("Inside DashboardAuthProvider: authenticate method +authentication=" + authentication);
Authentication auth =null;
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
try{
String[] principalStrArr = ((String)authentication.getPrincipal()).split(":");
//Convert the authentication principal object to a map
if (principalStrArr[0].equals("test1") && principalStrArr[1].equals("test1"))
{
String username = principalStrArr[0];
String password = principalStrArr[1];
final UserDetails principal = new AccessInfo(username, password, grantedAuths);
auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
logger.info("DashboardAuthProvider auth= " + auth);
}
else {
logger.info("Wrong credential");
return null;
}
}catch (Exception e){
logger.error(
"Exception occured in DashboardAuthProvider during authentication",
e);
}
return auth;
}
And here is my onAuthenticationSuccess:
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
super.onAuthenticationSuccess(request, response, authentication);
}
i have the following spring-security.xml file :-
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<http auto-config="true">
<intercept-url pattern="/Freelancer/**" access="ROLE_FREELANCE" />
<intercept-url pattern="/Client/**" access="ROLE_CLIENT" />
<intercept-url pattern="/Agency/**" access="ROLE_AGENCY" />
<intercept-url pattern="/Manager/**" access="ROLE_MANAGER" />
<intercept-url pattern="/User/**" access="ROLE_USER" />
<form-login default-target-url="/${role}" login-page="/login.jsp" />
<logout logout-url="/logout" logout-success-url="/" />
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select user_name,password, enabled from Users where user_name=?"
authorities-by-username-query="select u.user_name, u.role from Users u where u.user_name =?"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
what i want, i want to redirect the user to their workspace, for example if Client login then he will be redirected to the /Client/index.jsp, if Agency login, they will be redirected to the /Agency/index.jsp.
is there any way to access the role before, he will be redirected to their workspace in spring-security.xml file.
<form-login default-target-url="/${role}" login-page="/login.jsp" />
I have the directory structure similer to role.
have any idea.
Write a spring controller which will serve different pages to be shown based on user role. Write Authentication success handler class and write code to decide where to redirect based on roles.
First of all <form-login /> tag need to be changed.
<form-login login-page="/landing" authentication-success-handler-ref="authSuccessHandler" />
<beans:bean id="authSuccessHandler" class="com.package.AuthSuccessHandler" />
Remove default-target-url attribute. Let auth handler decide where to redirect the user.
Auth success handler class will be like :
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
#Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
// Get the role of logged in user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String role = auth.getAuthorities().toString();
String targetUrl = "";
if(role.contains("client")) {
targetUrl = "/client/index";
} else if(role.contains("agency")) {
targetUrl = "/agency/index";
}
return targetUrl;
}
}
This is a sample code. Change it as per your requirements.
You can use annotation based solution by using custom success handler like this:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
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.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
#Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
/*
* This method extracts the roles of currently logged-in user and returns
* appropriate URL according to his/her role.
*/
protected String determineTargetUrl(Authentication authentication) {
String url = "";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
if (isDba(roles)) {
url = "/db";
} else if (isAdmin(roles)) {
url = "/admin";
} else if (isUser(roles)) {
url = "/home";
} else {
url = "/accessDenied";
}
return url;
}
private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_ADMIN")) {
return true;
}
return false;
}
private boolean isDba(List<String> roles) {
if (roles.contains("ROLE_DBA")) {
return true;
}
return false;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
And security config as:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
CustomSuccessHandler customSuccessHandler;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER')")
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
.usernameParameter("ssoId").passwordParameter("password")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
It is better to check roles with equals in granted authority, contains may fail if multiple role exist with a same part.
Add authentication success handler in form login config like below:
<http auto-config="true">
<intercept-url pattern="/Freelancer/**" access="ROLE_FREELANCE" />
<intercept-url pattern="/Client/**" access="ROLE_CLIENT" />
<intercept-url pattern="/Agency/**" access="ROLE_AGENCY" />
<intercept-url pattern="/Manager/**" access="ROLE_MANAGER" />
<intercept-url pattern="/User/**" access="ROLE_USER" />
<form-login login-page='/login.html'
authentication-failure-url="/login.html?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"/>
<logout logout-url="/logout" logout-success-url="/" />
</http>
And the success handler goes like this:
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
protected Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug(
"Response has already been committed. Unable to redirect to "
+ targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isFreelance = false;
boolean isClient = false;
boolean isAgency = false;
boolean isManager = false;
Collection<? extends GrantedAuthority> authorities
= authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_FREELANCE")) {
isFreelance = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_CLIENT")) {
isClient = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_AGENCY")) {
isAgency = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_MANAGER")) {
isManager = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
}
}
if (isFreelance) {
return "freelance/homepage.html";
} else if (isClient) {
return "client/homepage.html";
} else if (isAgency) {
return "agency/homepage.html";
} else if (isManager) {
return "manager/homepage.html";
} else if (isUser) {
return "user/homepage.html";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
I am working on one project where I am using Spring Security and it authenticates user nicely from DB.
Now my need is I want to authenticate user using LDAP and Keep existing DB authentication as well.
Also, I can't use standard LDAP authentication way by using Spring security because I only have one function call to authenticate whether user is present or not by method like,
com.company.ldap.Authentication auth = new com.company.ldap.Authentication();
int status = auth.authenticate(userName, userPassword);
if I receive the status as 1 then user is authenticated otherwise not.
So for this scenario, I have created seperate url "/j_spring_facebook_security_check" (here name is facebook but actually it is for LDAP)
My applicationContext-Security File
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<security:http auto-config="true" use-expressions="true" access-denied-page="/accessDenied.jsp">
<security:form-login login-page="/index.jsp"
default-target-url="/jsp/home.jsp"
authentication-failure-handler-ref="authenticationFailureHandler" />
<security:intercept-url pattern="/jsp/listInBetweenPlaces.jsp"
access="permitAll" />
<security:intercept-url pattern="/jsp/home.jsp"
access="permitAll" />
<security:intercept-url pattern="/jsp/*"
access="isAuthenticated()" />
<security:logout logout-url="/j_spring_security_logout" logout-success-url="/index.jsp?logout=success"
invalidate-session="true" />
<security:custom-filter before="FORM_LOGIN_FILTER"
ref="facebookAuthenticationFilter" />
</security:http>
<bean id="facebookAuthenticationFilter" class="org.springframework.security.facebook.FacebookAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name = "authenticationSuccessHandler">
<bean class = "org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
<property name = "defaultTargetUrl" value = "/jsp/home.jsp" />
<property name = "alwaysUseDefaultTargetUrl" value = "true" />
</bean>
</property>
<property name = "authenticationFailureHandler">
<bean class = "org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name = "defaultFailureUrl" value = "/fb/failure.jsp" />
</bean>
</property>
</bean>
<bean id="ldapAuthenticationProvider" class="org.springframework.security.facebook.FacebookAuthenticationProvider">
<property name="roles" value="ROLE_FACEBOOK_USER" />
</bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider user-service-ref="customUserDetailsService">
<security:password-encoder hash="md5" />
</security:authentication-provider>
<security:authentication-provider ref="ldapAuthenticationProvider">
</security:authentication-provider>
</security:authentication-manager>
<bean id="customUserDetailsService" class="com.abc.carpool.authentication.CustomUserDetailsService">
</bean>
</beans>
FacebookAuthenticationFilter.java
public class FacebookAuthenticationFilter extends AbstractAuthenticationProcessingFilter implements ApplicationContextAware {
#Autowired
CarpoolService carpoolService=null;
public CarpoolService getCarpoolService() {
return carpoolService;
}
public void setCarpoolService(CarpoolService carpoolService) {
this.carpoolService = carpoolService;
}
public static final String DEFAULT_FILTER_PROCESS_URL = "/j_spring_facebook_security_check";
private ApplicationContext ctx;
protected FacebookAuthenticationFilter() {
super(DEFAULT_FILTER_PROCESS_URL);
}
public Authentication attemptAuthentication(HttpServletRequest req,
HttpServletResponse res) throws AuthenticationException,
IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String userName = request.getParameter("j_username");
String userPassword = request.getParameter("j_password");
System.out.println("Username and pswd is :"+userName + " " + userPassword);
System.out.println("SYS PATH :"+System.getenv("MC_ENV_PATH"));
User user = null;
try{
com.abc.ldap.Authentication auth = new com.abc.ldap.Authentication();
int status = auth.authenticate(userName, userPassword);
//int status=2;
if(status==1){
//CREATE NEW USER AND SAVE IN DB
}
}else{
throw new UsernameNotFoundException("Incorrect Email Id or Password.");
}
System.out.println("status is :"+status);
}catch (Exception e) {
System.out.println("Exception is "+e.getMessage());
e.printStackTrace();
return null;
}
System.out.println("FacebookAuthenticationFilter.attemptAuthentication() :"+userName + " " + userPassword);
UsernamePasswordAuthenticationToken upatToken = new UsernamePasswordAuthenticationToken(userName, userPassword);
AuthenticationManager authenticationManager = getAuthenticationManager();
Authentication auth = authenticationManager.authenticate(upatToken);
return auth;
}
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
this.ctx = ctx;
}
}
FacebookAuthenticationProvider .java
public class FacebookAuthenticationProvider implements AuthenticationProvider {
private String[] roles;
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
System.out.println("FacebookAuthenticationProvider.authenticate()");
return authentication;
}
public boolean supports(Class<? extends Object> authentication) {
boolean supports = true;
return supports;
}
public void setRoles(String[] roles) {
this.roles = roles;
}
public String[] getRoles() {
return roles;
}
}
In the above case things are working fine, Control is going to Filter class and verifying for user using LDAP and if user is present then I am saving user one copy to my DB and want to go ahead with normal flow.
actually when I call
Authentication auth = authenticationManager.authenticate(upatToken);
from FacebookAuthenticationFilter, control, goes to CustomUserDetailsService class.
My need is CustomUserDetailsService is only for DB authentication, I don't want control to go there.
How to achieve this thing in a nice way.
AuthenticationProvider.supports(Class<? extends Object> authentication) can help you. At this moment you use UsernamePasswordAuthenticationToken for both cases (DB and LDAP). Both authentication providers supports this type so both are used. In a case of LDAP try to add your custom authentication object:
public class CustomLdapAuthenticationToken extends AbstractAuthenticationToken {
Then use it in your FacebookAuthenticationFilter instead of UsernamePasswordAuthenticationToken.
Change your FacebookAuthenticationProvider.supports(...) implementation:
public boolean supports(Class<? extends Object> authentication) {
boolean result = false;
if(authentication instanceof CustomLdapAuthenticationToken) {
result = true;
}
return result;
}
From this moment each authentication provider will process only corresponding authentication request.
As title says, i'm developing a web application that receives user authentication infos from an external application. A spring controller of my app gets user info and stores it in session. I want to authenticate this user inside Spring Security and then use his roles to grant/deny access to urls like
<intercept-url pattern="/myprotectedpage*" access="hasRole('rightrole')" />
I read some tutorials speaking about PRE_AUTH_FILTER and UserDetailsService but i can't get the point. What is the application lifecycle of Spring Security? Which classes are involved?
I need some full working samples.
There are lots of tuts out there for the same, just need to google properly.
Anyway the best i have found till date (for almost all spring tuts) is Krams and here's the one for basic spring security.
http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html
For Implementing UserDetailService here's the link
http://krams915.blogspot.in/2012/01/spring-security-31-implement_5023.html
Some others are :
Spring By Example
MK Young
And SpringSource Site itself
EDIT
This is how my own application does the authentication (Please note that i dont use external authentication, I simpply get details from DB but i guess it should not be much of an issue).
My security-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled">
</global-method-security>
<http use-expressions="true">
<intercept-url pattern="/favicon.ico" access="permitAll" />
<intercept-url pattern="/static/**" access="permitAll"/>
<intercept-url pattern="/login.jsp*" access="permitAll"/>
<intercept-url pattern="/Admin/**" access="hasAnyRole('ROLE_SUPER_USER')"/>
<intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_SUPER_USER','ROLE_ADMIN'"/>
<form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" />
<http-basic/>
<logout logout-success-url="/login.jsp"/>
<remember-me user-service-ref="loginService" /
</http>
<authentication-manager>
<authentication-provider user-service-ref="loginService">
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="loginService" class="com.indyaah.service.LoginService">
</beans:bean>
<beans:bean id="authService" class="com.indyaah.service.AuthService" />
</beans:beans>
Now as you see i have specified a bean named loginService as my authentication provider which is a bean for class com.indyaah.service.LoginService.
The code for the same is :
Pl Note I have truncated unnecessary code
package com.indyaah.service;
..
#Service
public class LoginService implements UserDetailsService {
....
/**
* Implementation for custom spring security UserDetailsService
*/
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
logger.debug("Inside get member by username");
if (userName != null) {
Member memberVO = memberMapper.getMemberByUsername(userName);
if (memberVO != null) {
ArrayList<String> authList = memberRolesMapper.getMemberRoles(memberVO.getMemberId());
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : authList) {
System.out.println(role);
authorities.add(new GrantedAuthorityImpl(role.toString()));
}
if (memberVO.getEnabled()) {
User user = new User(memberVO.getUserName(), memberVO.getPassword(), true, true, true, true, authorities);
return user;
} else {
logger.error("User with login: " + userName + " not Enabled in database. Authentication failed for user ");
throw new UsernameNotFoundException("User Not Enabled");
}
} else {
logger.error("User with login: " + userName + " not found in database. Authentication failed for user ");
throw new UsernameNotFoundException("user not found in database");
}
} else {
logger.error("No User specified in the login ");
throw new UsernameNotFoundException("No username specified");
}
}
}
Note 2 things over here.
I get the user details (in my case from DB, yours may be diff.) and put it under a new org.springframework.security.core.userdetails.User object which is then returned by the method to spring security.
Also the authorities, (which I load separately from DB as per my DB architecture, again your scenario may vary) and pass it to spring security via same User object.
implement a service that holds the user information.
#Service
public class UserAuthenticationInfoService {
private final Map<String, UserInfo> infos = new HashMap<String, UserInfo>();
public void addUserInfo(UserInfo userInfo){
infos.put(userInfo.getUsername(), userInfo);
}
public UserInfo getUserInfo(String username) {
return infos.get(username);
}
}
your controllers populates the UserAuthenticationInfoService service with the user information which you receive from your external application.
then implement a custom UserDetailsService to acces these information.
public class CustomerUserDetailsService implements UserDetailsService {
#Autowired
private UserAuthenticationInfoService service;
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
UserInfo info = service.getUserInfo(userName);
return new User(info.getUsername(), info.getPassword(), info.getAuthorities());
}
}
and setup spring security context to use this UserDetailsService (you'll find it in the spring security documentation)
You can implement your own Custom AuthenticationManager and Custom UsernamePasswordAuthenticationFilter. This is simple example but it can give you an idea also for your information this is very sensitive part of security context:)
Simply create beans in your spring_security.xml:
<http entry-point-ref="authenticationProcessingFilterEntryPoint"
use-expressions="true">
<custom-filter ref="sessionManagementFilter" before="SESSION_MANAGEMENT_FILTER" />
<custom-filter ref="customUsernamePasswordAuthenticationFilter"
position="FORM_LOGIN_FILTER" />
<session-management
session-authentication-strategy-ref="sas"></session-management>
</http>
<beans:bean id="authenticationProcessingFilterEntryPoint"
class="org.springframework.security.web.authentication.AuthenticationProcessingFilterEntryPoint">
<beans:property name="loginFormUrl" value="/login" />
</beans:bean>
<beans:bean id="sas"
class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy" />
<beans:bean id="customAuthenticationManager"
class="my.package.security.CustomAuthenticationManager" />
<beans:bean id="customUsernamePasswordAuthenticationFilter"
class="my.package.security.CustomUsernamePasswordAuthenticationFilter">
<beans:property name="sessionAuthenticationStrategy"
ref="sas" />
<beans:property name="authenticationManager" ref="customAuthenticationManager" />
<beans:property name="authenticationSuccessHandler">
<beans:bean
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/main.xhtml" />
</beans:bean>
</beans:property>
<beans:property name="authenticationFailureHandler">
<beans:bean
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<beans:property name="defaultFailureUrl" value="/login.xhtml" />
</beans:bean>
</beans:property>
</beans:bean>
<beans:bean id="sessionManagementFilter"
class="org.springframework.security.web.session.SessionManagementFilter">
<beans:constructor-arg name="securityContextRepository"
ref="httpSessionSecurityContextRepository" />
</beans:bean>
<beans:bean id="httpSessionSecurityContextRepository"
class="org.springframework.security.web.context.HttpSessionSecurityContextRepository" />
When you implement CustomUsernamePasswordAuthenticationFilter override Authentication and add your external logic:
public final class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response){
CustomAuthentication auth = new CustomAuthentication();
// set details of current user
auth.setDetails(new WebAuthenticationDetails(request));
auth.setAuthenticated(true);
auth.setUserName(username);
// set authentication to current security session
LOGGER.info("Setting authentication into existing security context");
SecurityContextHolder.getContext().setAuthentication(auth);
// if validation done return generated authentication
return auth;
}
}
Then generated authentication object will be handled by authentication manager:
public final class CustomAuthenticationManager implements AuthenticationManager {
/*
* (non-Javadoc)
*
* #see org.springframework.security.authentication.AuthenticationManager#
* authenticate(org.springframework.security.core.Authentication)
*/
private static final Logger LOGGER = LoggerFactory.getLogger(CustomUsernamePasswordAuthenticationFilter.class);
private final BadCredentialsException badCredentialsException = new BadCredentialsException("Invalid username/password");
#Override
public Authentication authenticate(Authentication authentication) {
//check if user has valid authentication
if (authentication == null) {
LOGGER.debug("Null authentication");
throw badCredentialsException;
}
//Check mandatory fields
if (!Validator.isValidString((String) authentication.getPrincipal()) || !Validator.isValidString((String) authentication.getCredentials())) {
LOGGER.debug("Null/blank username/credential");
throw badCredentialsException;
}
//Check if there is any role assigned into user
if (authentication.getAuthorities() != null && authentication.getAuthorities().size() < 1) {
LOGGER.debug("No authority found");
throw badCredentialsException;
}
//Validate role
//IF ROLE VALIDATION REQUIRED YOU CAN HANDLE IT HERE
boolean authorityValid = false;
LOGGER.info("Validating user authentication. Total grantedAuth size: " + authentication.getAuthorities().size());
for (GrantedAuthority g : authentication.getAuthorities()) {
if (!authorityValid) {
//Testing purpose one type role available, when exact roles prepared create enum types
authorityValid = g.getAuthority().equals("ROLE_LDAP_AUTHENTICATED");
}
}
//if none of role matching to required throw exception
if(!authorityValid){
LOGGER.debug("User has authority but none of them matching");
throw badCredentialsException;
}
LOGGER.info("Final validation done returning authentication");
return authentication;
}
}
Then if required you can override default authentication object too,if roles dynamically located here is where you handle:
public final class CustomAuthentication implements Authentication {
/**
*
*/
private static final long serialVersionUID = 1L;
private transient String userName;
private transient boolean authenticated;
private transient Object details;
private static final transient String ROLE = "ROLE_LDAP_AUTHENTICATED";
/*
* (non-Javadoc)
*
* #see java.security.Principal#getName()
*/
#Override
public String getName() {
return this.userName; //for dynamic username logic here
}
//IF ROLES DYNAMICALLY ALLOCATED ASSIGN IT HERE, HERE IS WHERE YOU READ FROM INTERCEPT URL
/*
* (non-Javadoc)
*
* #see org.springframework.security.core.Authentication#getAuthorities()
*/
#Override
public Collection<GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
auths.add(new GrantedAuthority() {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public String getAuthority() {
if (authenticated) {
return ROLE;
}
return null;
}
});
return auths;
}
/*
* (non-Javadoc)
*
* #see org.springframework.security.core.Authentication#getCredentials()
*/
#Override
public Object getCredentials() {
//TODO: a specific algorithm can be stored
return userName + " is ldap authenticated user";
}
/*
* (non-Javadoc)
*
* #see org.springframework.security.core.Authentication#getDetails()
*/
#Override
public Object getDetails() {
return this.details;
}
/*
* (non-Javadoc)
*
* #see org.springframework.security.core.Authentication#getPrincipal()
*/
#Override
public Object getPrincipal() {
return userName;
}
/*
* (non-Javadoc)
*
* #see org.springframework.security.core.Authentication#isAuthenticated()
*/
#Override
public boolean isAuthenticated() {
return this.authenticated;
}
/*
* (non-Javadoc)
*
* #see
* org.springframework.security.core.Authentication#setAuthenticated(boolean
* )
*/
#Override
public void setAuthenticated(boolean arg0) {
this.authenticated = arg0;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setDetails(Object details) {
this.details = details;
}
}