]> git.argeo.org Git - lgpl/argeo-commons.git/blob - CmsLogin.java
d93a952254d1aa3c233bc3b0c1845b14bc276d3d
[lgpl/argeo-commons.git] / CmsLogin.java
1 package org.argeo.cms;
2
3 import static org.argeo.cms.internal.kernel.KernelConstants.SPRING_SECURITY_CONTEXT_KEY;
4
5 import java.util.Collections;
6 import java.util.List;
7
8 import javax.servlet.http.HttpSession;
9
10 import org.apache.commons.logging.Log;
11 import org.apache.commons.logging.LogFactory;
12 import org.argeo.cms.internal.kernel.KernelConstants;
13 import org.eclipse.rap.rwt.RWT;
14 import org.springframework.security.authentication.AnonymousAuthenticationToken;
15 import org.springframework.security.authentication.AuthenticationManager;
16 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
17 import org.springframework.security.core.Authentication;
18 import org.springframework.security.core.authority.SimpleGrantedAuthority;
19 import org.springframework.security.core.context.SecurityContextHolder;
20 import org.springframework.security.core.userdetails.User;
21 import org.springframework.security.core.userdetails.UserDetails;
22
23 /** Gateway for user login, can also generate the related UI. */
24 public class CmsLogin {
25 private final static Log log = LogFactory.getLog(CmsLogin.class);
26 private AuthenticationManager authenticationManager;
27 private String systemKey = KernelConstants.DEFAULT_SECURITY_KEY;
28
29 public void logInAsAnonymous() {
30 // TODO Better deal with anonymous authentication
31 try {
32 List<SimpleGrantedAuthority> anonAuthorities = Collections
33 .singletonList(new SimpleGrantedAuthority(
34 KernelHeader.USERNAME_ANONYMOUS));
35 UserDetails anonUser = new User("anonymous", "", true, true, true,
36 true, anonAuthorities);
37 AnonymousAuthenticationToken anonToken = new AnonymousAuthenticationToken(
38 systemKey, anonUser, anonAuthorities);
39 Authentication authentication = authenticationManager
40 .authenticate(anonToken);
41 SecurityContextHolder.getContext()
42 .setAuthentication(authentication);
43 } catch (Exception e) {
44 throw new CmsException("Cannot authenticate", e);
45 }
46 }
47
48 public void logInWithPassword(String username, char[] password) {
49 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
50 username, password);
51 Authentication authentication = authenticationManager
52 .authenticate(token);
53 SecurityContextHolder.getContext().setAuthentication(authentication);
54 HttpSession httpSession = RWT.getRequest().getSession();
55 httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY,
56 SecurityContextHolder.getContext());
57 if (log.isDebugEnabled())
58 log.debug("Authenticated as " + authentication);
59 }
60
61 public void setAuthenticationManager(
62 AuthenticationManager authenticationManager) {
63 this.authenticationManager = authenticationManager;
64 }
65
66 public void setSystemKey(String systemKey) {
67 this.systemKey = systemKey;
68 }
69
70 }