Programmatically login from a link in spring security - spring-security

i am trying to automatically authorization without login in spring security. The user would be authorized by clicking a link in a website.
I have a class UserLoginService that called from spring-security xml file like this;
<authentication-manager>
<authentication-provider user-service-ref="userLoginService" >
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="userLoginService"
class="tr.com.enlil.formdesigner.server.guvenlik.UserLoginService">
</beans:bean>
UserLoginService class;
public class UserLoginService implements UserDetailsService {
private static Logger logger = Logger.getLogger(InitServlet.class);
#Autowired
private IKullaniciBusinessManager iKullaniciBusinessManager;
/**
* {#inheritDoc}
*/
#Override
public UserDetails loadUserByUsername(String username) {
try {
Kullanici kullanici = new Kullanici();
kullanici.setKullaniciAdi(username);
Kullanici kullaniciBusinessManager = iKullaniciBusinessManager.getirKullaniciAdinaGore(kullanici);
User user = new User();
if (kullaniciBusinessManager != null && kullaniciBusinessManager.getAktifmi()) {
user.setUsername(kullaniciBusinessManager.getKullaniciAdi());
user.setPassword(kullaniciBusinessManager.getSifre());
user.setKullanici(kullaniciBusinessManager);
List<String> yetkiListesi = new ArrayList<String>();
List<GrantedAuthority> grandAuthorities = new ArrayList<GrantedAuthority>();
//TODO yetkilerle alakalı birşey yapmak gerekebilir.
for (String yetki : yetkiListesi) {
GrantedAuthorityImpl g = new GrantedAuthorityImpl(yetki);
grandAuthorities.add(g);
}
user.setAuthorities(grandAuthorities);
}
return user;
} catch (Exception e) {
logger.error("Kullanici alinirken hata olustu!!", e);
}
return null;
}
public static void autoLogin(User user, HttpServletRequest request, AuthenticationManager authenticationManager) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
user.getPassword(), user.getAuthorities());
// generate session if one doesn't exist
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
// setting role to the session
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext());
}
}
I found autoLogin method from Make Programmatic login without username/password?. But i dont know, from where can i call this method and will this code help me.
Thanks in advance.

You will have to create your own implementation of AbstractPreAuthenticatedProcessingFilter. The method getPreAuthenticatedPrincipal(HttpServletRequest request) will have the request where you can get your credentials from. You will need to return a subject if it is a valid user or null if it is not. Your implementation of UserDetailsService will transform the subject to a UserDetails object.

Related

How to add(overwrite) expiry time for oAuth2 access token in spring + java

I have a situation where the authorisation server is not returning expires_in field to the token response, but the token expires after certain time. Can I set this manually somewhere in my code ?
Below is my code for ROPC.
#Bean(name = “myROPCRestTemplate")
public OAuth2RestTemplate myROPCRestTemplate() {
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(myPasswordResourceDetails());
restTemplate.setAccessTokenProvider(getAccessTokenProvider());
return restTemplate;
}
private AccessTokenProvider getAccessTokenProvider() {
ResourceOwnerPasswordAccessTokenProvider resourceOwnerPasswordAccessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
return new AccessTokenProviderChain(Collections.singletonList(resourceOwnerPasswordAccessTokenProvider));
}
private OAuth2ProtectedResourceDetails myPasswordResourceDetails() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setAccessTokenUri(tokenUrl);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setUsername(username);
resource.setPassword(password);
resource.setClientAuthenticationScheme(AuthenticationScheme.form);
resource.setGrantType("password");
return resource;
}
I know this is an old question but maybe someone need to override AccessToken implementation which is DefaultOAuth2AccessToken under spring security oauth2 autoconfigure project, here is the one workaround that we used
Our approach was not extend default access token or override new accesstoken from scratch with using OAuth2AccessToken, instead create ClientContext which is extend DefaultOAuth2ClientContext and make necessary changes on same AccessToken during set operation.
Here is the code sample, first extends client context, create a new component and make neccessary changes in setAccessToken (in this case setting exiparation) :
#Component
public class MyOAuth2ClientContext extends DefaultOAuth2ClientContext {
#Override
public void setAccessToken(OAuth2AccessToken accessToken) {
DefaultOAuth2AccessToken dxpAccessToken = new DefaultOAuth2AccessToken(accessToken);
dxpAccessToken.setExpiration(new Date());
super.setAccessToken(dxpAccessToken);
}
}
And finaly use this context when constructing your OAuth2RestTemplate use your own context :
#Configuration
public class MyWebConfiguration {
#Resource MyOAuth2ClientContext myOAuth2ClientContext;
#Bean
#ConfigurationProperties("spring.security.oauth2.client.authserver")
protected ClientCredentialsResourceDetails authServerDetails() {
return new ClientCredentialsResourceDetails();
}
#Bean(name = "myRestTemplate")
protected RestTemplate myRestTemplate() {
return new OAuth2RestTemplate(authServerDetails(), myOAuth2ClientContext);
}
}
Hope this will be helpful.
You could register a DefaultTokenServices bean and configure it:
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setAccessTokenValiditySeconds(3600); // valid for one hour
return defaultTokenServices;
}

SpringSecurity WithSecurityContext MockMvc OAuth2 always unauthorised

I have followed the following links to try and test OAuth2 #PreAuthorise(hasAnyRole('ADMIN', 'TEST') for example but I can't any of the tests to pass or even authenticate.
When I try to access the end point with admin (or any role) it will never authenticate properly. Am I missing something obvious, it seems I have everything just as it is in the examples. I have also tried another alternative to the WithSecurityContext Factory with OAuth Specific Authentication and still no luck. Any help would be appreciated.
https://stackoverflow.com/a/31679649/2594130
and
http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test
My Controller I'm testing
#RestController
#RequestMapping("/bookmark/")
public class GroupBookmarkController {
#Autowired
BookmarkService bookmarkService;
/**
* Get list of all bookmarks
*/
#RequestMapping(value = "{groupId}", method = RequestMethod.GET)
#PreAuthorize("hasAnyRole(['ADMIN', 'USER'])")
public ResponseEntity<List<Bookmark>> listAllGroupBookmarks(#PathVariable("groupId") String groupId) throws BookmarkNotFoundException {
List<Bookmark> bookmarks = bookmarkService.findAllBookmarksByGroupId(groupId);
return new ResponseEntity<>(bookmarks, HttpStatus.OK);
}
...
}
My Test class
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = BookmarkServiceApplication.class)
#WebAppConfiguration
public class BookmarkServiceApplicationTests {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void loadData() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.alwaysDo(print())
.build();
}
#Test
#WithMockCustomUser(username = "test")
public void getBookmarkAuthorised() throws Exception {
mockMvc.perform(get("/bookmark/nvjdbngkjlsdfngkjlfdsnlkgsd"))
.andExpect(status().is(HttpStatus.SC_OK));
// always 401 here
}
}
My BookmarkServiceApplication
#SpringBootApplication
#EnableResourceServer
public class BookmarkServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BookmarkServiceApplication.class, args);
}
}
My WithSecurityContextFactory
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockCustomUser> {
#Override
public SecurityContext createSecurityContext(WithMockCustomUser customUser) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
UserDetails principal = new User(customUser.username(), "password", true, true, true, true, grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(
principal, principal.getPassword(), principal.getAuthorities());
context.setAuthentication(authentication);
return context;
}
}
My WithSecurityContext Annotation
#Retention(RetentionPolicy.RUNTIME)
#WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public #interface WithMockCustomUser {
String username() default "user";
String name() default "Test User";
}
As per #RobWinch 's reply
Hi #RobWinch I've tried you suggestion with the stateless flag, this helped with part of the answer. However in your reply to this question [Spring OAuth and Boot Integration Test] (https://stackoverflow.com/a/31679649/2594130) you mention
You no longer need to worry about running in stateless mode or not
Why is it that I need to still add the stateless false, is this a bug or are we using it slightly differently?
The other thing I needed to do to get this to work was adding OAuth2Request and OAuth2Authentication to the WithSecurityContextFactory as you can see in the following
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockOAuthUser> {
#Override
public SecurityContext createSecurityContext(WithMockOAuthUser withClient) {
// Get the username
String username = withClient.username();
if (username == null) {
throw new IllegalArgumentException("Username cannot be null");
}
// Get the user roles
List<GrantedAuthority> authorities = new ArrayList<>();
for (String role : withClient.roles()) {
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException("roles cannot start with ROLE_ Got " + role);
}
authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
// Get the client id
String clientId = withClient.clientId();
// get the oauth scopes
String[] scopes = withClient.scope();
Set<String> scopeCollection = Sets.newSet(scopes);
// Create the UsernamePasswordAuthenticationToken
User principal = new User(username, withClient.password(), true, true, true, true, authorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
principal.getAuthorities());
// Create the authorization request and OAuth2Authentication object
OAuth2Request authRequest = new OAuth2Request(null, clientId, null, true, scopeCollection, null, null, null,
null);
OAuth2Authentication oAuth = new OAuth2Authentication(authRequest, authentication);
// Add the OAuth2Authentication object to the security context
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(oAuth);
return context;
}
}
The problem is that OAuth2AuthenticationProcessingFilter will clear the SecurityContext if it is marked as stateless. To workaround this configure it to allow the state to be populated externally (i.e. stateless = false).
to add some more infos how to set stateless to false:
in your ResourceServerConfigurerAdapter do the following:
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.stateless(false);
}
which worked for me.

Social login, spring-security-oauth2 and spring-security-jwt?

I'm developing a rest service which is going to be available in browser via
browser single page app and a mobile app. At the moment my service is working
without spring at all. The oauth2 client is implemented inside filters so to say "by hand".
I'm trying to migrate it to spring boot.
Much manuals read and much info googled and I'm trying to understand if the
following is actually possible for a customer:
Authorize with facebook oauth2 service (and get an access_token) with all the help
from spring-security-oauth2.
Create a JWT and pass it to the client so that all further requests are
backed with the JWT.
Since in my opinion spring boot is all about the configuration and declarations
I want to understand if this is possible with spring-security-oauth2 and
spring-security-jwt?
I'm not askng for a solution but just a yes/no from knowledge bearers since I'm deep in
the spring manuals and the answer becomes further...
short answer: Yes you can do it!
You have to add security dependencies to your build.gradle or pom.xml file:
compile "org.springframework.boot:spring-boot-starter-security"
compile "org.springframework.security:spring-security-config"
compile "org.springframework.security:spring-security-data"
compile "org.springframework.security:spring-security-web"
compile "org.springframework.social:spring-social-security"
compile "org.springframework.social:spring-social-google"
compile "org.springframework.social:spring-social-facebook"
compile "org.springframework.social:spring-social-twitter"
then you have to add social config to your project alongside with your security config:
#Configuration
#EnableSocial
public class SocialConfiguration implements SocialConfigurer {
private final Logger log = LoggerFactory.getLogger(SocialConfiguration.class);
private final SocialUserConnectionRepository socialUserConnectionRepository;
private final Environment environment;
public SocialConfiguration(SocialUserConnectionRepository socialUserConnectionRepository,
Environment environment) {
this.socialUserConnectionRepository = socialUserConnectionRepository;
this.environment = environment;
}
#Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator,
ConnectionRepository connectionRepository) {
ConnectController controller = new ConnectController(connectionFactoryLocator, connectionRepository);
controller.setApplicationUrl(environment.getProperty("spring.application.url"));
return controller;
}
#Override
public void addConnectionFactories(ConnectionFactoryConfigurer connectionFactoryConfigurer, Environment environment) {
// Google configuration
String googleClientId = environment.getProperty("spring.social.google.client-id");
String googleClientSecret = environment.getProperty("spring.social.google.client-secret");
if (googleClientId != null && googleClientSecret != null) {
log.debug("Configuring GoogleConnectionFactory");
connectionFactoryConfigurer.addConnectionFactory(
new GoogleConnectionFactory(
googleClientId,
googleClientSecret
)
);
} else {
log.error("Cannot configure GoogleConnectionFactory id or secret null");
}
// Facebook configuration
String facebookClientId = environment.getProperty("spring.social.facebook.client-id");
String facebookClientSecret = environment.getProperty("spring.social.facebook.client-secret");
if (facebookClientId != null && facebookClientSecret != null) {
log.debug("Configuring FacebookConnectionFactory");
connectionFactoryConfigurer.addConnectionFactory(
new FacebookConnectionFactory(
facebookClientId,
facebookClientSecret
)
);
} else {
log.error("Cannot configure FacebookConnectionFactory id or secret null");
}
// Twitter configuration
String twitterClientId = environment.getProperty("spring.social.twitter.client-id");
String twitterClientSecret = environment.getProperty("spring.social.twitter.client-secret");
if (twitterClientId != null && twitterClientSecret != null) {
log.debug("Configuring TwitterConnectionFactory");
connectionFactoryConfigurer.addConnectionFactory(
new TwitterConnectionFactory(
twitterClientId,
twitterClientSecret
)
);
} else {
log.error("Cannot configure TwitterConnectionFactory id or secret null");
}
// jhipster-needle-add-social-connection-factory
}
#Override
public UserIdSource getUserIdSource() {
return new AuthenticationNameUserIdSource();
}
#Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
return new CustomSocialUsersConnectionRepository(socialUserConnectionRepository, connectionFactoryLocator);
}
#Bean
public SignInAdapter signInAdapter(UserDetailsService userDetailsService, JHipsterProperties jHipsterProperties,
TokenProvider tokenProvider) {
return new CustomSignInAdapter(userDetailsService, jHipsterProperties,
tokenProvider);
}
#Bean
public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository, SignInAdapter signInAdapter) {
ProviderSignInController providerSignInController = new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, signInAdapter);
providerSignInController.setSignUpUrl("/social/signup");
providerSignInController.setApplicationUrl(environment.getProperty("spring.application.url"));
return providerSignInController;
}
#Bean
public ProviderSignInUtils getProviderSignInUtils(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) {
return new ProviderSignInUtils(connectionFactoryLocator, usersConnectionRepository);
}
}
then you have to write adapter for your social login:
public class CustomSignInAdapter implements SignInAdapter {
#SuppressWarnings("unused")
private final Logger log = LoggerFactory.getLogger(CustomSignInAdapter.class);
private final UserDetailsService userDetailsService;
private final JHipsterProperties jHipsterProperties;
private final TokenProvider tokenProvider;
public CustomSignInAdapter(UserDetailsService userDetailsService, JHipsterProperties jHipsterProperties,
TokenProvider tokenProvider) {
this.userDetailsService = userDetailsService;
this.jHipsterProperties = jHipsterProperties;
this.tokenProvider = tokenProvider;
}
#Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
try {
UserDetails user = userDetailsService.loadUserByUsername(userId);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
user,
null,
user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
String jwt = tokenProvider.createToken(authenticationToken, false);
ServletWebRequest servletWebRequest = (ServletWebRequest) request;
servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
} catch (AuthenticationException ae) {
log.error("Social authentication error");
log.trace("Authentication exception trace: {}", ae);
}
return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
private Cookie getSocialAuthenticationCookie(String token) {
Cookie socialAuthCookie = new Cookie("social-authentication", token);
socialAuthCookie.setPath("/");
socialAuthCookie.setMaxAge(10);
return socialAuthCookie;
}
}
you can find sample project in my github:
https://github.com/ksadjad/oauth-test

Encrypting the password before authetication

I have to authenticate a SOAP message that sends passwords in plain text with the encrypted password from the database. We use HTTPS for all traffic so the entire message in encrypted.
Anyway, I have implemented the following SI configuration, which works until Spring tries to match the passwords. Since the SOAP password is plain text and the db passowrd is encrypted, I must encrypt the password before Spring authenticates. I have service methods to do this already implemented.
<bean id="SOAPSecurityValidationCallbackHandler" class="org.springframework.ws.soap.security.wss4j.callback.SpringSecurityPasswordValidationCallbackHandler">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="userDetailsService" class="com.ps.snt.ws.security.SNTUserDetailsService" />
UserDetailsService implementation:
public class SNTUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("In security callback " + username);
boolean valid = true;
Integer zoneID = null;
StringBuffer errorMessages = new StringBuffer();
if(StringUtils.isEmpty(username)) {
// TODO wil lthis ever happen, does framework check first?
errorMessages.append("Username token cannot be empty");
valid = false;
} else {
Pattern pattern = Pattern.compile("^[\\w]+#+\\d\\d\\d\\d\\d");
Matcher matcher = pattern.matcher(username);
if(!matcher.matches()) {
valid = false;
errorMessages.append("Username token must be in the format 'user#zone'.");
}
else {
String[] parts = username.split("#");
username = parts[0];
zoneID = Integer.parseInt(parts[1]);
}
}
if(valid && username != null && zoneID != null) {
LoginService loginService = new LoginService();
ApplicationUserDO user = loginService.getUserByUsername(zoneID.toString(), username);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new GrantedAuthorityImpl("ROLE_USER"));
UserDetails userDetails = new User(user.getUsername(),
user.getPassword(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
grantedAuths );
return userDetails;
} else {
System.out.println("Authetnication failed!");
throw new UsernameNotFoundException("Epic fail!");
}
}
}
The user details service does what its supposed to - it returns a user with the password from the database.
I tried overidding handleUSernameTokenPrincipal in SpringSecurityPasswordValidationCallbackHandler to set the password to the encrypted version, but this method never gets called. Overriding handleUsername is not useful as I do not have access to the original password.
I would like to keep the details service and use this callback, but I need to set the password in the principal to the encrypted version before authentication.
Ideally I would want to set the password after validation of the SOAP header but before the user details service is called. Not sure if I can do this with another interceptor, but I do not want to parse through XML and et it that way. I would like to do it in a somewhat safe manner.
I found a solution using an authentication manager on the callback:
<bean id="SOAPSecurityValidationCallbackHandler"
class="org.springframework.ws.soap.security.xwss.callback.SpringPlainTextPasswordValidationCallbackHandler">
<property name="authenticationManager" ref="CommonAuthenticationManager" />
</bean>
The AuthenticationManager interface must implement one method - authenticate:
public class CommonAuthenticationManager implements AuthenticationManager {
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
String username = auth.getName();
String password = (String) auth.getCredentials();
... encrypt password
... validate against DB
// this will be available in the message flow to any channel
return new UsernamePasswordAuthenticationToken(auth.getName(),
auth.getCredentials(), grantedAuths);
}
}

Auto login and redirect after registration

I am creating a movie rental application using JSF 2.0 with Primefaces 3.4.1 as frontend. After a user is successfully registered, I need to automatically login with the newly created ID and redirect to the home page.
Currently, I am doing this way:
#ManagedBean
#ViewScoped
public class RegistrationBean extends BaseBean implements Serializable
{
...
public String register()
{
String nextPage = null;
User userDetails = new User();
try
{
BeanUtils.copyProperties(userDetails, this);
int registrationID = getServiceLocator().getUserService().registerUser(userDetails);
LOGGER.info("Registered user successfully. Registration ID - {}", registrationID);
// auto login
LoginBean loginBean = (LoginBean)FacesUtils.getManagedBean("loginBean");
loginBean.setUserId(userID);
loginBean.setPassword(password);
loginBean.login();
}
catch (Exception e) {
LOGGER.error("Error during registration - " + e.getMessage());
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, null,
FacesUtils.getValueFromResource(RESOURCE_BUNDLE, REGISTRATION_FAIL));
FacesContext.getCurrentInstance().addMessage(null, message);
}
return nextPage;
}
}
LoginBean :
#ManagedBean
#SessionScoped
public class LoginBean extends BaseBean implements Serializable
{
...
public String login()
{
FacesContext ctx = FacesContext.getCurrentInstance();
try
{
currentUser = getServiceLocator().getUserService().findUser(userID);
if (currentUser == null)
{
ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, null,
FacesUtils.getValueFromResource(RESOURCE_BUNDLE, UNKNOWN_LOGIN)));
return (userID = password = null);
}
else
{
if (EncryptionUtils.compareHash(password, currentUser.getEncrPass())) {
return INDEX + "?faces-redirect=true";
}
else
{
ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, null,
FacesUtils.getValueFromResource(RESOURCE_BUNDLE, AUTH_FAIL)));
return null;
}
}
}
catch (Exception e)
{
final String errorMessage = "Error occured during login - " + e.getMessage();
LOGGER.error(errorMessage);
ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, null, errorMessage));
}
return null;
}
}
Above approach in register() method is, no doubt, wrong and insecure. Is there any way I can achieve the same in a cleaner way ??
Implementation using f:viewParam
RegistrationBean
int registrationID = getServiceLocator().getUserService().registerUser(userDetails);
LOGGER.info("Registered user successfully. Registration ID - {}", registrationID);
nextPage = LOGIN + "?faces-redirect=true&id=" + registrationID;
login.xhtml
<f:metadata>
<f:viewParam name="id" value="#{loginBean.regID}" />
<f:event listener="#{loginBean.autoLogin}" type="preRenderView"></f:event>
</f:metadata>
LoginBean
private int regID;
...
public void autoLogin()
{
if (regID > 0 && !FacesContext.getCurrentInstance().isPostback())
{
currentUser = getServiceLocator().getUserService().findUser(regID);
NavigationHandler navHandler = FacesUtils.getApplication().getNavigationHandler();
navHandler.handleNavigation(FacesContext.getCurrentInstance(), null, INDEX + "?faces-redirect=true");
}
}
So let us assume you are having three pages
Register/User Signup
Login
Home page
Here successful registration need auto login and needs to be redirected to home page but usually manual login is must after registration.
Anyhow, I would suggest you to separate login credential check in separate method in a facade class or you can have it in LoginBean too.
public User doLogin(String userName, String password) {
// query user
// match with password
// return null if not found or not matched
}
Add navigation-rule in faces-config.xml for registration bean and login bean
<navigation-case>
<from-outcome>loginSuccess</from-outcome>
<to-view-id>/home.xhtml</to-view-id>
<redirect/>
</navigation-case>
In both registration bean and login bean call doLogin method then if user found set navigation
NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
nh.handleNavigation(facesContext, null, "loginSuccess");

Resources