I have a xml code like follows
<http auto-config="false" use-expressions="true" create-session="ifRequired" entry-point-ref="loginUrlAuthenticationEntryPoint">
<custom-filter position="FORM_LOGIN_FILTER" ref="authenticationProcessingFilter" />
<custom-filter before="PRE_AUTH_FILTER" ref="socialAuthenticationFilter" />
<intercept-url pattern="/blah/404-error" access="permitAll()" />
<intercept-url pattern="/blah/500-error" access="permitAll()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<remember-me services-ref="rememberMeServices" key="blah" />
<logout logout-url="/blah/logout" logout-success-url="/blah/signin" />
</http>
<beans:bean id="authenticationProcessingFilter" class="in.security.ReCaptchaAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="filterProcessesUrl" value="/blah/authentication" />
<beans:property name="authenticationSuccessHandler" ref="authenticationSuccessHandler" />
<beans:property name="authenticationFailureHandler" ref="authenticationFailureHandler" />
<beans:property name="privateKey" value="key" />
</beans:bean>
I am not sure how i can configure the above xml configuration using spring code
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
}
}
I can normally see that the examples code contains the following
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
or
auth
.jdbcAuthentication()
.dataSource(dataSource)
.withDefaultSchema()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
But i am not using either inmemory authentication as well as jdbc authentication. But i am not using any of this authentication. I am using filters....
I am not sure what to put inside the configureGlobal method.
Related
I have one application using spring 4 and all the methods are rest(using RestController). I used spring-security(role based) for login and authentication url.
Below is my spring-security.xml
<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
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.1.xsd">
<security:http auto-config="true" use-expressions="true">
<security:form-login login-page="/public/login"
default-target-url="/auth/userhome" authentication-failure-url="/public/fail2login" always-use-default-target="true"/>
<security:intercept-url pattern="/index.jsp" access="permitAll" />
<security:intercept-url pattern="/public/**" access="permitAll" />
<security:intercept-url pattern="/resources/**" access="permitAll" />
<security:logout logout-success-url="/public/logout" />
<security:intercept-url pattern="/auth/**" access="fullyAuthenticated" />
<security:intercept-url pattern="/**" access="denyAll" />
<security:session-management
session-fixation-protection="migrateSession" invalid-session-url="/login">
<security:concurrency-control
max-sessions="1" expired-url="/login" />
</security:session-management>
</security:http>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="hbUserDetailService">
<security:password-encoder hash="plaintext" />
</security:authentication-provider>
</security:authentication-manager>
</beans>
Service:
package com.arat.budget.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.arat.budget.dao.UserDao;
import com.arat.budget.model.UserRoles;
import com.arat.budget.model.Users;
#Service
public class HbUserDetailsService implements UserDetailsService {
#Autowired
private UserDao userDao;
#SuppressWarnings("unchecked")
#Transactional
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
Users user = userDao.findByUserName(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoleses());
return buildUserForAuthentication(user, authorities);
}
// Converts com.mkyong.users.model.User user to
// org.springframework.security.core.userdetails.User
private User buildUserForAuthentication(Users user, List<GrantedAuthority> authorities) {
return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<UserRoles> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (UserRoles userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
return Result;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
#RestController
public class PostAuthController {
#RequestMapping(value = "/auth/userhome", method = RequestMethod.GET)
public String executeSecurity(ModelMap model, Principal principal) {
String name = principal.getName();
model.addAttribute("author", name);
model.addAttribute("message",
"Welcome To Login Form Based Spring Security Example!!!");
return "auth/welcome";
}
}
I am able to login without any issue. But I have one controller with /auth/employee/{id} and request mapping.
Since /auth/** is fullyAuthenticated so how other application can access the rest endpoint
#RestController
#RequestMapping(value="/auth")
public class EmployeeController{
#RequestMapping("/employee/{id}",method=RequestMethod.GET)
public List<Employee> getEmployee(#PathVariable int id){
return userDao.getEmployee(id);
}
}
Could you please help me how can I access /auth/employee/1001 in another application without login?
Note: I am using tiles to render the page in this application
You can use Basic Authentication for this. Extend BasicAuthenticationEntryPoint class and create a custom implementation of it.
public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
#Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
//Authentication failed, send error response.
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 : " + authException.getMessage());
}
#Override
public void afterPropertiesSet() throws Exception {
setRealmName("MY_TEST_REALM");
super.afterPropertiesSet();
}
}
For more info refer this.
Hope this helps.
I got my solution.
I created a separate api url which will expose only resources and added basic auth filter.
My spring-security.xml looks like below.
<?xml version="1.0"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2
http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<!-- Oauth start -->
<http pattern="/oauth/token" create-session="stateless"
authentication-manager-ref="clientAuthenticationManager">
<intercept-url pattern="/oauth/token"
access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<custom-filter ref="clientCredentialsTokenEndpointFilter"
after="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<http pattern="/api/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager">
<anonymous enabled="false" />
<intercept-url pattern="/api/**" access="ROLE_APP" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<beans:bean id="oauthAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<beans:property name="realmName" value="test" />
</beans:bean>
<beans:bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<beans:property name="realmName" value="test/client" />
<beans:property name="typeName" value="Basic" />
</beans:bean>
<beans:bean id="oauthAccessDeniedHandler"
class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<beans:bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<beans:property name="authenticationManager" ref="clientAuthenticationManager" />
</beans:bean>
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
<beans:constructor-arg>
<beans:list>
<beans:bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<beans:bean class="org.springframework.security.access.vote.RoleVoter" />
<beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</beans:list>
</beans:constructor-arg>
</beans:bean>
<authentication-manager id="clientAuthenticationManager">
<authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>
<authentication-manager alias="authenticationManager">
<authentication-provider
user-service-ref="hbUserDetailService">
<password-encoder hash="plaintext" />
</authentication-provider>
<!-- <authentication-provider>
<jdbc-user-service data-source-ref="spring_db_DataSource"/>
</authentication-provider> -->
</authentication-manager>
<beans:bean id="clientDetailsUserService"
class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<beans:constructor-arg ref="clientDetails" />
</beans:bean>
<beans:bean id="tokenStore"
class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />
<beans:bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<beans:property name="tokenStore" ref="tokenStore" />
<beans:property name="supportRefreshToken" value="true" />
<beans:property name="accessTokenValiditySeconds" value="120" />
<beans:property name="clientDetailsService" ref="clientDetails" />
</beans:bean>
<beans:bean id="userApprovalHandler"
class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
<beans:property name="tokenServices" ref="tokenServices" />
</beans:bean>
<oauth:authorization-server
client-details-service-ref="clientDetails" token-services-ref="tokenServices"
user-approval-handler-ref="userApprovalHandler">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
<oauth:resource-server id="resourceServerFilter"
resource-id="test" token-services-ref="tokenServices" />
<oauth:client-details-service id="clientDetails">
<oauth:client client-id="restapp"
authorized-grant-types="authorization_code,client_credentials"
authorities="ROLE_APP" scope="read,write,trust" secret="secret" />
<oauth:client client-id="restapp"
authorized-grant-types="password,authorization_code,refresh_token,implicit"
secret="restapp" authorities="ROLE_APP" />
</oauth:client-details-service>
<!-- <global-method-security
pre-post-annotations="enabled" proxy-target-class="true">
<expression-handler ref="oauthExpressionHandler" />
</global-method-security> -->
<oauth:expression-handler id="oauthExpressionHandler" />
<oauth:web-expression-handler id="oauthWebExpressionHandler" />
<!-- Oauth end -->
<!-- Form based security starts-->
<http auto-config="true" use-expressions="true"
authentication-manager-ref="authenticationManagerForRest">
<form-login login-page="/public/login"
default-target-url="/auth/userhome" authentication-failure-url="/public/fail2login"
always-use-default-target="true" />
<intercept-url pattern="/index.jsp"
access="permitAll" />
<intercept-url pattern="/public/**"
access="permitAll" />
<intercept-url pattern="/resources/**"
access="permitAll" />
<logout logout-success-url="/public/logout" />
<access-denied-handler error-page="/403.html"/>
<intercept-url pattern="/auth/**"
access="fullyAuthenticated" />
<intercept-url pattern="/**" access="denyAll" />
<session-management
session-fixation-protection="migrateSession" invalid-session-url="/login">
<concurrency-control
max-sessions="1" expired-url="/login" />
</session-management>
</http>
<authentication-manager alias="authenticationManagerForRest">
<authentication-provider
user-service-ref="hbUserDetailService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>
<!-- Form based security ends -->
</beans:beans>
deploy the project and to get the access token
localhost:8080/<context>/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=<uer>&password=<password>
it will give the access token using which we can involke the rest end point
How do I fire my method on authentication success?
I wanted to update my database column 'last login date'. Looked around on google but still can't understand how it should be done.
Here is my spring-security.xml
<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.2.xsd"
xmlns:security="http://www.springframework.org/schema/security">
<beans:bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<beans:property name="url" value="jdbc:mysql://localhost:3306/myDB"/>
<beans:property name="username" value="root"/>
<beans:property name="password" value="root"/>
</beans:bean>
<!-- login page are exempted from security-->
<security:http pattern="/login" security="none"/>
<security:http auto-config="true">
<intercept-url pattern="/page1" access="ROLE_USER_ADMIN,ROLE_ADMIN,ROLE_PAGE1" />
<intercept-url pattern="/page2" access="ROLE_USER_ADMIN,ROLE_ADMIN,ROLE_PAGE2" />
<intercept-url pattern="/page3" access="ROLE_USER_ADMIN,ROLE_ADMIN,ROLE_PAGE3" />
<intercept-url pattern="/*" access="ROLE_USER_ADMIN,ROLE_ACCOUNT" /> <!--/** all url -->
<security:session-management>
<security:concurrency-control
max-sessions="2"
expired-url="/login" />
</security:session-management>
<!-- access deny for non privileged user -->
<access-denied-handler error-page="/access-denied" />
<!-- Logout -->
<logout logout-success-url="/login?logout" />
</security:http>
<beans:bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<!-- After login, return to the last visited page -->
<beans:property name="useReferer" value="true" />
</beans:bean>
<beans:bean id="authenticationSuccessHandlerWithoutReferer" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<!-- After login, stay to the same page -->
<beans:property name="useReferer" value="false" />
</beans:bean>
<beans:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource1"
users-by-username-query="query-for-username-and-password"
authorities-by-username-query="query-for-username-enabled-authority" />
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
I am new to Spring Security. Hope someone could help me out.
EDIT
#Component
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
#Autowired
AppUserDAO appUserDAO;
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String a = df.format(new Date());
System.out.println(authentication.getName()+"### "+a);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getPrincipal().toString();
appUserDAO.updateLastLoginAndIp(a, username);
}
}
You can override authenticationSuccessHandler with any custom implementation you wanted to perform. Here you want to update user login date or some other similar activities
public class CustomAuthenticationSuccessHandler extends
SavedRequestAwareAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException,ServletException {
super.onAuthenticationSuccess(request, response, authentication);
//Now add your custom logic to update database
}
}
Now you need to update authenticationSuccessHandler confiuguration in xml file as shown below.
<beans:bean id="authenticationSuccessHandler" class="yourpackage.CustomAuthenticationSuccessHandler">
<beans:property name="useReferer" value="true" />
</beans:bean>
Optionally,
<beans:bean id="authenticationSuccessHandlerWithoutReferer" class="yourpackage.CustomAuthenticationSuccessHandler">
<beans:property name="useReferer" value="false" />
</beans:bean>
I trying to implement custom authorization based on spring security.
Here is the config.xml:
<global-method-security pre-post-annotations="enabled" />
<http use-expressions="true">
<form-login login-page="/wellcome/" login-processing-url="/login" default-target-url="/"
username-parameter="email" password-parameter="password" />
<remember-me key="skyhandling" token-validity-seconds="-1" />
<logout invalidate-session="true" logout-success-url="/" logout-url="/logout"/>
<intercept-url pattern="/administration/**" access="authenticated"/>
<intercept-url pattern="/wellcome/" access="permitAll"/>
<intercept-url pattern="/login" access="permitAll"/>
<intercept-url pattern="/css/**" access="permitAll"/>
<intercept-url pattern="/images/**" access="permitAll"/>
<intercept-url pattern="/javascript/**" access="permitAll"/>
</http>
<beans:bean id="authenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService"/>
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="authenticationProvider" />
</beans:list>
</beans:property>
</beans:bean>
<beans:bean class="com.test.service.UserDetailsExtendedService" id="userDetailsService" />
<beans:bean class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"
id="passwordEncoder" />
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>
User details service:
#Service("userDetailsService")
#SuppressWarnings("deprecation")
public class UserDetailsExtendedService implements UserDetailsService {
#Autowired
private UsersDAO dao;
/**
*
* #param user
* #return
*/
private User prepare(com.test.User user) {
boolean enabled = user.getState().equals(UserState.Active);
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (UserRole r: user.getRoles()) {
authorities.add(new GrantedAuthorityImpl(r.getName()));
}
return new UserDetailsExtended(user.getEmail(), user.getPassword(), user.getNickname(), enabled,
enabled, enabled, enabled, authorities);
}
/**
*
* #param email
* #return
*/
#Transactional(readOnly = true)
public User loadUserByUsername(final String email)
throws UsernameNotFoundException, DataAccessException {
com.test.User user = dao.getByEmail(email);
if (user == null)
throw new UsernameNotFoundException(email);
return prepare(user);
}
}
Everything works fine. But when I add
#Autowired
private UserDetailsExtendedService useDetailsService;
into Controller class the applicaton starts to fail with:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.test.service.UserDetailsExtendedService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
What I missed? Thank you
UPD#1:
<context:annotation-config />
<context:component-scan base-package="com.test.service" />
<bean id="usersDao" class="com.test.dao.UsersDAO" />
<bean id="eventsLogDao" class="com.test.dao.EventsLogDAO" />
<bean id="employeesDao" class="com.test.dao.EmployeesDAO" />
<bean id="dictionariesDao" class="com.test.dao.DictionariesDAO" />
In your configuration you have a com.ejl.skyhandling.service.UserDetailsExtendedService but
in your bean you are trying to access com.test.service.UserDetailsExtendedService which is obviously another type.
Please check your imports.
Since you're qualifying #Service with value "userDetailsService" make sure the #Autowired is
#Autowired
private UserDetailsExtendedService userDetailsService;
You currently are missing the r in the variable name -> useDetailsService
Everything works like a charm the first time I login after deployment of my Spring security app. But after the first logout, I can't login again until the service is restarted! Also it seems as if the login was successful, as I can see the users data being loaded in the hibernate sql-log.
Here the relevant code fragments:
applicationContext-security.xml:
<global-method-security pre-post-annotations="enabled" />
<http auto-config="true" use-expressions="true" security="none" pattern="/bookmark/add" />
<http auto-config="true"
use-expressions="true"
access-denied-page="/user/login"
disable-url-rewriting="true">
<intercept-url pattern="/dashboard/**" access="isAuthenticated()" />
<intercept-url pattern="/user/**" access="permitAll" />
<intercept-url pattern="/**" access="permitAll" />
<form-login
default-target-url="/dashboard"
login-page="/user/login"
login-processing-url="/user/doLogin"
authentication-failure-url="/user/login/error"
username-parameter="email"
password-parameter="password" />
<logout logout-success-url="/user/logout"
logout-url="/user/doLogout"
invalidate-session="true"
delete-cookies="true" />
<remember-me services-ref="rememberMeServices" key="myfancysalt" />
<session-management invalid-session-url="/user/login">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="loginUserDetailsService">
<password-encoder ref="passwordEncoder" hash="sha-256">
<salt-source system-wide="myfancysalt" />
</password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder" />
<beans:bean id="rememberMeFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
<beans:property name="rememberMeServices" ref="rememberMeServices"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
</beans:bean>
<beans:bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
<beans:property name="userDetailsService" ref="loginUserDetailsService"/>
<beans:property name="key" value="myfancysalt"/>
</beans:bean>
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<beans:property name="key" value="myfancysalt"/>
</beans:bean>
LoginController:
#RequestMapping(value = "login", method = RequestMethod.GET)
public String login(Principal principal) {
if (principal != null) { // If user is already logged in, redirect him
return "redirect:/dashboard";
}
return "user/login";
}
#RequestMapping(value = {"login/error", "/user/doLogin"})
public ModelAndView processLogin(Principal principal) {
if (principal != null) { // If user is already logged in, redirect him
return new ModelAndView("redirect:/dashboard", null);
}
HashMap map = new HashMap();
map.put("error", true);
return new ModelAndView("user/login", map);
}
#RequestMapping(value = "logout")
public ModelAndView logout() {
return new ModelAndView("user/logout");
}
The necessary filter in web.xml is present.
Any help is very much appreciated!
### EDIT ###:
The problem lied in the concurrent session limitation. After I removed the following part from the applicationcontext-security.xml, everything works fine. Can someone tell me what's wrong with it? (I just copy/pasted it from some howto).
<session-management invalid-session-url="/user/login">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>
You can try to do:
principal == null
before you logout.
Hi I am new to Spring security 3 but with the help of this site I successfully developed Authentication and Authorization. Now I want to remove intercept-url pattern from my context-security.xml. I am looking to fetch authorities for specific user form database and create dynamically. Here i did...
in context-security.xml
<beans:bean id="filterSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor">
<custom-filter before="FIRST" ref="requestMappings"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="accessDecisionManager" ref="accessDecisionManager" />
<beans:property name="objectDefinitionSource" ref="requestMappings" />
</beans:bean>
<beans:bean id="requestMappings" class="com.nmmc.common.security.repository.RequestMappingFactoryBean" />
<http auto-config="true" once-per-request="false">
<!-- Restrict URLs based on role -->
<intercept-url pattern="/login.works" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/login/validate.works" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/css/*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<form-login login-page="/login.works" login-processing-url="/j_spring_security_check"
default-target-url="/login/validate.works"
authentication-failure-url="/login.works" />
<logout logout-url="/j_spring_security_logout"
logout-success-url="/login.works" invalidate-session="true" />
<session-management invalid-session-url="/login.works"
session-fixation-protection="none">
<concurrency-control max-sessions="50"
error-if-maximum-exceeded="true" />
</session-management>
</http>
<authentication-manager>
<authentication-provider ref="customAuthenticationProvider"></authentication-provider>
</authentication-manager>
<beans:bean id="customAuthenticationProvider"
class="com.nmmc.common.security.repository.CustomAuthenticationProvider"></beans:bean>
in RequestMappingFactoryBean
import org.springframework.beans.factory.FactoryBean;
public class RequestMappingFactoryBean implements FactoryBean{
private final static String EOL = System.getProperty("line.separator");
public Object getObject() throws Exception
{
StringBuffer sb = new StringBuffer();
sb.append("CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON");
sb.append(EOL);
sb.append("PATTERN_TYPE_APACHE_ANT");
sb.append(EOL);
sb.append("/**login.works=IS_AUTHENTICATED_ANONYMOUSLY");
sb.append(EOL);
sb.append("/user/**=ROLE_ADMIN");
return sb.toString();
}
public Class getObjectType()
{
return String.class;
}
public boolean isSingleton()
{
return true;
}
}
Also when I remove ref from
<custom-filter before="FIRST" ref="requestMappings"/>
then it gives error that ref must be define also if i define it and run my app it gives error like
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Security namespace does not support decoration of element [custom-filter]
thats why i define as given.
Is there any changes in my code to run it?
Read the first answer at How to dynamically decide <intercept-url> access attribute value in Spring Security?
It has an outline of the solution.