]> git.argeo.org Git - lgpl/argeo-commons.git/blob - OsSpringLoginModule.java
23bf163ac1c90003276b5d94ca347139a4955fde
[lgpl/argeo-commons.git] / OsSpringLoginModule.java
1 /*
2 * Copyright (C) 2007-2012 Mathieu Baudier
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.argeo.security.equinox;
17
18 import java.util.Map;
19
20 import javax.security.auth.Subject;
21 import javax.security.auth.callback.CallbackHandler;
22 import javax.security.auth.login.LoginException;
23
24 import org.argeo.security.OsAuthenticationToken;
25 import org.springframework.security.Authentication;
26 import org.springframework.security.AuthenticationManager;
27 import org.springframework.security.context.SecurityContextHolder;
28 import org.springframework.security.providers.jaas.SecurityContextLoginModule;
29
30 /** Login module which caches one subject per thread. */
31 public class OsSpringLoginModule extends SecurityContextLoginModule {
32 // private final static Log log =
33 // LogFactory.getLog(OsSpringLoginModule.class);
34
35 private AuthenticationManager authenticationManager;
36
37 private Subject subject;
38
39 public OsSpringLoginModule() {
40
41 }
42
43 @SuppressWarnings("rawtypes")
44 public void initialize(Subject subject, CallbackHandler callbackHandler,
45 Map sharedState, Map options) {
46 super.initialize(subject, callbackHandler, sharedState, options);
47 this.subject = subject;
48 }
49
50 public boolean login() throws LoginException {
51 // thread already logged in
52 if (SecurityContextHolder.getContext().getAuthentication() != null)
53 return super.login();
54
55 OsAuthenticationToken oat = new OsAuthenticationToken();
56 Authentication authentication = authenticationManager.authenticate(oat);
57 registerAuthentication(authentication);
58 return super.login();
59 }
60
61 @Override
62 public boolean logout() throws LoginException {
63 subject.getPrincipals().clear();
64 return super.logout();
65 }
66
67 /**
68 * Register an {@link Authentication} in the security context.
69 *
70 * @param authentication
71 * has to implement {@link Authentication}.
72 */
73 protected void registerAuthentication(Object authentication) {
74 SecurityContextHolder.getContext().setAuthentication(
75 (Authentication) authentication);
76 }
77
78 public void setAuthenticationManager(
79 AuthenticationManager authenticationManager) {
80 this.authenticationManager = authenticationManager;
81 }
82 }