How to retrieve pK using spring security - spring

I implement this method of the UserDetailService interface,
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException, DataAccessException {
final EmailCredential userDetails = persistentEmailCredential
.getUniqueEmailCredential(username);
if (userDetails == null) {
throw new UsernameNotFoundException(username + "is not registered");
}
final HashSet<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
for (UserRole role:userDetails.getAccount().getRoles()) {
authorities.add(new GrantedAuthorityImpl(role.getRole()));
}
return new User(userDetails.getEmailAddress(), userDetails
.getPassword(), true, true, true, true,
authorities);
}
In the security context I do some thing like this:
<!-- Login Info -->
<form-login default-target-url='/dashboard.htm' login-page="/login.htm"
authentication-failure-url="/login.htm?authfailed=true"
always-use-default-target='false' />
<logout logout-success-url="/login.htm" invalidate-session="true" />
<remember-me user-service-ref="emailAccountService" key="fuellingsport" />
<session-management>
<concurrency-control max-sessions="1" />
</session-management>
</http>
Now I want to pop out the Pk of the logged in user.
How can I show it in my jsp pages?
Any idea?

I guess you are looking for something like this, which can be used in jsp.
<security:authentication property="principal.username"/>

You can implement your own class extending User with required fields and return it from UserDetailsService.
Then you can access these fields as pointed out by Raghuram:
<security:authentication property="principal.pk"/>

Related

How to set user role in Spring Security 3?

I am working on JAVA EE technologies to learn JSF-Spring-Hibernate vs...
I am trying to do web application with diffirent user roles. Now, I have only one user role ROLE_USER. I could not change that role. I tried debug mod to understand how we set this role but I could not understand where it is happening.
So, my main problem is I can not create any other ROLE in my application. If I do not use <secured attributes="ROLE_USER" /> in my flow (I am using spring web-flow) everyone can reach that page. If I do only ROLE_USER. But I want to create new role named ROLE_ADMIN and only let ROLE_ADMIN to reach that page.
NOTE: I did not add all files here cause is spoken to me that only add related classes and files. If you need extra information please let me know.
This is the tutorial soruce code that I am following.
https://code.google.com/p/jee-tutorial-youtube/source/browse/
security-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<security:http auto-config="true">
<security:form-login login-page="/app/main"
default-target-url="/app/account" />
<security:logout logout-url="/app/logout"
logout-success-url="/app/main" />
</security:http>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="userServiceImp">
<security:password-encoder hash="md5" />
</security:authentication-provider>
</security:authentication-manager>
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userServiceImp" />
<property name="hideUserNotFoundExceptions" value="false" />
</bean>
<bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<constructor-arg>
<ref bean="daoAuthenticationProvider" />
</constructor-arg>
</bean>
This is my UserAuthenticationProviderServiceImp class where I authenticatethe the user.
public boolean processUserAuthentication(Users user) {
try {
Authentication request = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
return true;
} catch(AuthenticationException e) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "Sorry!"));
return false;
}
}
And I figure out that this function, im my Service class, is called in processUserAuthentication.Then I thought this is the function where Roles are setted.
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
Users user = userDao.loadUserByUserName(userName);
if (user == null) {
throw new UsernameNotFoundException(String.format(
getMessageBundle().getString("badCredentials"), userName));
}
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("USER_ROLE"));
User userDetails = new User(user.getUserName(), user.getPassword(),
authorities);
return userDetails;
}
Update:
In my project I have to use this syntax to create roles: ROLE_X where x is any string. Example; we can have ROLE_MYNAME but we can not have juts MYNAME or MYNAME_ROLE as role. It has to start with ROLE_. I am still trying to find what couses this problem. I will update If I found any answer.
EDIT:
There is an detailed explanation why we has to use ROLE_ in this page;
http://bluefoot.info/howtos/spring-security-adding-a-custom-role-prefix/
Right now USER_ROLE is hardcoded in your application. Ideally User to Role mapping would come from Authorities table in database. This mapping info then can be retrieved using a DB query and then added to the authorities collection.
authorities.add(loadUserAuthorities(user.getUsername()));
protected List<GrantedAuthority> loadUserAuthorities(String username) {
List<GrantedAuthority> authorities = null;
Object[] params = { username };
authorities = authoritiesByUsernameMapping.execute(params); // Query to get Authorities
return authorities;
}
Spring Security DB schema

Spring Security 3.2 - Adding Signup Form to Login Page

I have integrated Spring Security login successfuly to my wb application. However, I would like to have in the login page, in addition to login form, a signup form.
In order to do validation I need to pass to that form the object SignupForm which represents my form.
How can I do it? I have tried so many approaches and nothing works.
Please help....
ApplicationContext.xml
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list><value>classpath:com/harryfwong/config/messages</value></list>
</property>
</bean>
message.properties in com.harryfwong.config resource package
username.required=Username is required
password.required=Password is required
passwordconfirm.mustmatch=Password must match
email.required=Email is required
Spring Validator
<!-- language: java -->
public class SignUpFormValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return SignUpForm.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "username.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
SignUpForm form = (SignUpForm) target;
if (!StringUtils.isBlank(form.getPassword())) {
if (!form.getPassword().equals(form.getPasswordConfirm())) {
errors.rejectValue("passwordConfirm", "passwordconfirm.mustmatch");
}
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
}
}
Controller
<!-- language: java -->
#RequestMapping(method=RequestMethod.GET, value="signup")
public String signup(#ModelAttribute("form") SignUpForm form) {
if (form == null) {
form = new SignUpForm();
}
return "auth/signup";
}
#RequestMapping(method=RequestMethod.POST, value="signup")
public String signupSuccess(#ModelAttribute("form") SignUpForm form, BindingResult result, HttpServletRequest request) {
SignUpFormValidator suValidator = new SignUpFormValidator();
suValidator.validate(form, result);
if (result.hasErrors()) {
return signup(form);
} else {
authenticateUserAndSetSession(form, request);
return "auth/signupSuccess";
}
}
External Reference Login after signup: Auto login after successful registration
What does your SS configuration currently look like?
<form-login
login-page="/login"
login-processing-url="/loginProcess"
default-target-url="/landing"
always-use-default-target="false" />
Where /login is the request mapping
#RequestMapping(value="login")
public String login() {
// do something prior to display form below
return "auth/login";
}
auth/login.jsp
<form name='f' action="<c:url value='/loginProcess' />"
method='POST'>
Not sure what your security context config looks like - this is a response to your issue about not getting to the signup page
<http use-expressions="true">
<intercept-url pattern="/login" access="permitAll"/>
<intercept-url pattern="/loggedout" access="permitAll"/>
<intercept-url pattern="/signup" access="permitAll"/>
<intercept-url pattern="/" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
...
</http>

Getting logged in users with sessionRegistry not work when manually authenticate

I use spring security3 and spring mvc3 to build an web project. There is page called index.jsp, login user name and online user count will be displayed on
the top of this screen. There are 2 ways to login the system:
from login page, use default configuration post by 'j_spring_security_check'
ajax login with manually authentication
When I use login page to login into index page, both of count of online information and user name show correctly.
But when I use ajax login (manually authenticate), problem occurs: count of online user don't updated, it always displaying 0 while user name can show properly.
Part of the controller:
#Autowired
#Qualifier("authenticationManager")
AuthenticationManager authenticationManager;
#Autowired
SecurityContextRepository repository;
#RequestMapping(value="/ajaxLogin")
#ResponseBody
public String performLogin(
#RequestParam("j_username") String username,
#RequestParam("j_password") String password,
HttpServletRequest request, HttpServletResponse response) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
try {
Authentication auth = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
repository.saveContext(SecurityContextHolder.getContext(), request, response);
logger.info("Authentication successfully! ");
return "{\"status\": true}";
} catch (BadCredentialsException ex) {
return "{\"status\": false, \"error\": \"Bad Credentials\"}";
}
}
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.0.3.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/index" access="permitAll" />
<form-login login-page="/login" default-target-url="/index"
authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
<session-management invalid-session-url="/index">
<concurrency-control max-sessions="1"
error-if-maximum-exceeded="false" />
</session-management>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="
select login_id,login_pwd, is_enabled
from t_user where login_id=?"
authorities-by-username-query="
select u.login_id, r.authority from t_user u, t_roles r
where u.u_id = r.u_id and u.login_id =? " />
</authentication-provider>
</authentication-manager>
Method I used to get online login user count:
public class BaseController {
protected Logger logger = Logger.getLogger(this.getClass());
#Autowired
SessionRegistry sessionRegistry;
#ModelAttribute("numUsers")
public int getNumberOfUsers() {
logger.info("in getNumberOfUsers() ...");
return sessionRegistry.getAllPrincipals().size();
}
}
Code used to show login user name:
<div>
<security:authorize ifAllGranted="ROLE_USER">
<p>Welcome <security:authentication property="principal.username" />!
Logout</p>
</security:authorize>
</div>
code used to show count of logged in users:
<div style="color:#3CC457">
${numUsers} user(s) are logged in!
</div>
I guess that because when I manually authenticate, spring security not create new session for the user. I validate it by write customized SessionCounterListener.
public class SessionCounterListener implements HttpSessionListener {
private Logger logger = Logger.getLogger(this.getClass());
private static int totalActiveSessions;
public static int getTotalActiveSession(){
return totalActiveSessions;
}
#Override
public void sessionCreated(HttpSessionEvent event) {
totalActiveSessions++;
logger.info("sessionCreated - add one session into counter" + event.getSession().getId());
}
#Override
public void sessionDestroyed(HttpSessionEvent event) {
totalActiveSessions--;
logger.info("sessionDestroyed - deduct one session from counter" + event.getSession().getId());
}
}
Below is key content of log file for the action sequence: normal login -> normal logout -> ajax login -> ajax logout.
sessionDestroyed - deduct one session 1spueddcmdao019udc43k3uumw
sessionCreated - add one session 14nro6bzyjy0x1jtvnqjx31v1
sessionDestroyed - deduct one session 14nro6bzyjy0x1jtvnqjx31v1
sessionCreated - add one session e6jqz5qy6412118iph66xvaa1
Actually, ajax login/logout not give any output.
So now, how can I get correct login user count? And why the different authenticate ways has different method to deal with session? Any help will be appreciated.
As you are manually adding Principal to SecurityContext, it will not add user to SessionRegistry. You need to add user session to SessionRegistry manually.
SecurityContextHolder.getContext().setAuthentication(auth);
sessionRegistry.registerNewSession(request.getSession().getId(), auth.getPrincipal());
Hope it helps!!
In your Spring spring-security.xml file, the URL for the AJAX authentication (/ajaxLogin) is not explicitly allowed. Thus the request should be blocked by Spring. I would suggest to add this:
<intercept-url pattern="/ajaxLogin" access="permitAll" />

Spring Security - Redirect if already logged in

I'm new to Spring:
I do not want authenticated user from accessing the login page. What is the proper way to handle redirects for the '/login' if the user is already authenticated? Say, I want to redirect to '/index' if already logged in.
I have tried 'isAnonomous()' on login, but it redirects to access denied page.
<security:http auto-config="true" use-expressions="true" ...>
<form-login login-processing-url="/resources/j_spring_security_check"
default-target-url="/index"
login-page="/login" authentication-failure-url="/login?login_error=t" />
<logout logout-url="/resources/j_spring_security_logout" />
...
<security:intercept-url pattern="/login" access="permitAll" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
In the controller function of your login page:
check if a user is logged in.
then forward/redirect him to the index page in that case.
Relevant code:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
/* The user is logged in :) */
return new ModelAndView("forward:/index");
}
Update
Or in another scenario where the mapping may be containing path variable like #GetMapping(path = "/user/{id}") in this case you can implement this logic as well:
#GetMapping(value = "/login")
public String getLogin() throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
User loggedInUser = userService.findByEmail(auth.getName())
.orElseThrow(Exception::new);
/* The user is logged in :) */
return "redirect:/user/" + loggedInUser.getUserId();
}
return "login";
}
To successfully redirect from login page, if user is already logged in, add the following to your login.jsp:
Add a security taglib header to the top of your jsp:
<%#taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>
Then add the following tag inside your "head" tag (preferably near the top):
<sec:authorize access="isAuthenticated()">
<% response.sendRedirect("main"); %>
</sec:authorize>
This will redirect to main.html (or whatever your main .jsp is mapped to) if the user accessing the login page is already logged-in.
Doing this through a controller didn't work for me, since the valid login page practice is to let the spring security's "form-login" bean do all the redirecting work, so there was no login controller for me to modify.
login.xhtml
<h:head >
<f:metadata>
<f:event type="preRenderView" listener="#{loginBean.onPageLoad}"/>
</f:metadata>
</h:head>
loginBean
public void onPageLoad(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
try {
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
hey you can do that.
<h:head>
<sec:authorize access="isAuthenticated()">
<meta http-equiv="refresh" content="0;url=http://your index.xhtml url (full url)" />
</sec:authorize>
</h:head>
This method is very simple and convenient, is not it?

Spring Security: put additional attributes(properties) in the session on success Authentication

Just simple question: what is the best way to add attributes(properties) to the HttpSession on success authentication? The userID for example.
For now i'm using my own SimpleUrlAuthenticationSuccessHandler implementation in UsernamePasswordAuthenticationFilter and doing it like this:
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
PersonBean person = (PersonBean) auth.getPrincipal();
request.getSession().setAttribute("currentUserId", person .getId().toString());
super.onAuthenticationSuccess(request, response, auth);
But I dont think this is good approach as there is another ways to do authentication(RememberMe for example).
So what do I need to use here?
The answer was given on spring forum. Link.
Generally, need to implement an ApplicationListener which listens for succes events and put additional attributes in the session there.
But in my case its not required to store attributes in the session. I can retrieve userID like here:
var userId = ${pageContext.request.userPrincipal.principal.id}
Spring does all this for you, you'll have to create a table *persistent_logins*, here is a snippet from app context that might help. And the official doc's lay describe in detail what is required :
<security:http auto-config='true'>
<security:intercept-url pattern="/**" access="ROLE_USER" />
<security:form-login login-page="/Login"
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-url="/Login?login_error=1" />
<security:remember-me data-source-ref="dataSource"
user-service-ref="myUserService" />
</security:http>
and then you can access the principal object from your anywhere in your app, eg below shows the tag to output username in jsp :
<sec:authentication property="principal.username" />
and from your java code this can be done :
MyUser user = (MyUser) authentication.getPrincipal();

Resources