Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 228 Vote(s) - 3.61 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Auto login after successful registration

#1
i want to make an auto login after successful registration in spring
meaning:
i have a protected page which requires login to access them
and i want after registration to skip the login page and make an auto login so the user can see that protected page, got me ?
i am using spring 3.0 , spring security 3.0.2
how to do so ?
Reply

#2
I'm not sure if you are asking for this, but in your Spring Security configuration you can add a "remember-me" tag. This will manage a cookie in your client, so next time (if the cookie hasn't expired) you'll be logged automatically.

<http>
...
<remember-me />
</http>
Reply

#3
Just a comment to the first reply on how to autowire authenticationManager.

You need to set an alias when you declare authentication-manager in either your applicantion-servlet.xml or applicationContext-security.xml file:

<authentication-manager alias="authenticationManager>
<authentication-provider>
<user-service>
<user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="bob" password="bobspassword" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>

Also, when you authenticate, it may throw an AuthenticationException, so you need to catch it:

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
request.getSession();

token.setDetails(new WebAuthenticationDetails(request));

try{
Authentication auth = authenticationManager.authenticate(token);

SecurityContextHolder.getContext().setAuthentication(auth);
} catch(Exception e){
e.printStackTrace();
}

return "redirect:xxxx.htm";
Reply

#4
[Spring Monkey's answer works great][1] but I encountered a tricky problem when implementing it.

My problem was because I set the registration page to have "no security", eg:

<http pattern="/register/**" security="none"/>

I think this causes no SecurityContext initialized, and hence after user registers, the in-server authentication cannot be saved.

I had to change the register page bypass by setting it into IS_AUTHENTICATED_ANONYMOUSLY

<http authentication-manager-ref="authMgr">
<intercept-url pattern="/register/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
...
</http>

[1]:

[To see links please register here]

Reply

#5
1. Configure web.xml to allow Spring Security to handle forwards for a login processing url.
2. Handle registration request, e.g. create user, update ACL, etc.
3. Forward it with username and password to login processing url for authentication.
4. Gain benefits of entire Spring Security filter chain, e.g. session fixation protection.

Since forwards are internal, it will appear to the user as if they are registered and logged in during the same request.

If your registration form does not contain the correct username and password parameter names, forward a modified version of the request (using `HttpServletRequestWrapper`) to the Spring Security login endpoint.

In order for this to work, you'll have to modify your web.xml to have the Spring Security filter chain handle forwards for the `login-processing-url`. For example:

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<!-- Handle authentication for normal requests. -->
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Handle authentication via forwarding for internal/automatic authentication. -->
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/login/auth</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>

**[Source: mohchi blog][1]**

[1]:

[To see links please register here]

Reply

#6
This can be done with spring security in the following manner(semi-psuedocode):

import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

@Controller
public class SignupController
{

@Autowired
RequestCache requestCache;

@Autowired
protected AuthenticationManager authenticationManager;

@RequestMapping(value = "/account/signup/", method = RequestMethod.POST)
public String createNewUser(@ModelAttribute("user") User user, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
//After successfully Creating user
authenticateUserAndSetSession(user, request);

return "redirect:/home/";
}

private void authenticateUserAndSetSession(User user, HttpServletRequest request) {
String username = user.getUsername();
String password = user.getPassword();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

// generate session if one doesn't exist
request.getSession();

token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token);

SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
}
}


Update: to only contain how to create the session after the registration
Reply

#7
In Servlet 3+ you can simply do `request.login("username","password")` and if successful, redirect to whatever page you want. You can do the same for auto logout.

Here is the link to the section of the documentation that talks about this:

[To see links please register here]

Reply

#8
This is answer to above question
**In Controller:**

@RequestMapping(value = "/registerHere", method = RequestMethod.POST)
public ModelAndView registerUser(@ModelAttribute("user") Users user, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("register 3");

ModelAndView mv = new ModelAndView("/home");
mv.addObject("homePagee", "true");

String uname = user.getUsername();

if (userDAO.getUserByName(uname) == null) {

String passwordFromForm = user.getPassword();
userDAO.saveOrUpdate(user);

try {
authenticateUserAndSetSession(user, passwordFromForm, request);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

System.out.println("register 4");

log.debug("Ending of the method registerUser");
return mv;
}

**Further above method in controller is defined as:**

`private void authenticateUserAndSetSession(Users user, String passwor`dFromForm, HttpServletRequest request){

String username = user.getUsername();
System.out.println("username: " + username + " password: " + passwordFromForm);

UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());

UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, passwordFromForm, userDetails.getAuthorities());
request.getSession();

System.out.println("Line Authentication 1");

usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(request));

System.out.println("Line Authentication 2");

Authentication authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

System.out.println("Line Authentication 3");


if (usernamePasswordAuthenticationToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
System.out.println("Line Authentication 4");

}

request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.

System.out.println("Line Authentication 5");

session.setAttribute("username", user.getUsername());

System.out.println("Line Authentication 6");

session.setAttribute("authorities", usernamePasswordAuthenticationToken.getAuthorities());

System.out.println("username: " + user.getUsername() + "password: " + user.getPassword()+"authorities: "+ usernamePasswordAuthenticationToken.getAuthorities());

user = userDAO.validate(user.getUsername(), user.getPassword());
log.debug("You are successfully register");

}

Other answers didnt suggest to put it in try/catch so one does not realize why logic is not working as code runs...and nothing is there neither error or exception on console. So if you wont put it in try catch you wont get exception of bad credentials.
Reply

#9
<p>Using SecurityContextHolder.getContext().setAuthentication(Authentication) gets the job done but it will bypass the spring security filter chain which will open a security risk.</p>
<p>For e.g. lets say in my case when user reset the password, I wanted him to take to the dashboard without login again. When I used the above said approach, it takes me to dashboard but it bypassed my concurrency filter which I have applied in order to avoid concurrent login. Here is the piece of code which does the job:</p>

UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(empId, password);
Authentication auth = authenticationManager.authenticate(authToken);
SecurityContextHolder.getContext().setAuthentication(auth);

<p>Use login-processing-url attribute along with a simple change in web.xml</p>
<strong>security-xml</strong>

<form-login login-page="/login"
always-use-default-target="false"
default-target-url="/target-url"
authentication-failure-url="/login?error"
login-processing-url="/submitLogin"/>

<strong>web.xml</strong>


<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/submitLogin</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<p> By adding this piece of code in web.xml actually does the job of forwarding your explicit forward request which you will make during auto login and passing it to the chain of spring security filters.</p>
<p> Hope it helps </p>
Reply

#10
This is an alternative to the Servlet 3+ integration. If you're using Spring Security's form login, then you can simply delegate to your login page. For example:

@PostMapping("/signup")
public String signUp(User user) {
// encode the password and save the user
return "forward:/login";
}

Assuming you have `username` and `password` fields in your form, then the 'forward' will send those parameters and Spring Security will use those to authenticate.

The benefit I found with this approach is that you don't duplicate your `formLogin`'s `defaultSuccessUrl` (example security setup below). It also cleans up your controller by not requiring a `HttpServletRequest` parameter.

@Override
public void configure(HttpSecurity http) {
http.authorizeRequests()
.antMatchers("/", "/signup").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home", true)
.permitAll();
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through