File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\jenkins\security\ApiTokenFilter.java.html

1 package jenkins.security;
2
3 import hudson.model.User;
4 import hudson.security.ACL;
5 import hudson.util.Scrambler;
6 import org.acegisecurity.context.SecurityContext;
7 import org.acegisecurity.context.SecurityContextHolder;
8
9 import javax.servlet.Filter;
10 import javax.servlet.FilterChain;
11 import javax.servlet.FilterConfig;
12 import javax.servlet.ServletException;
13 import javax.servlet.ServletRequest;
14 import javax.servlet.ServletResponse;
15 import javax.servlet.http.HttpServletRequest;
16 import javax.servlet.http.HttpServletResponse;
17 import java.io.IOException;
18
19 /**
20 * {@link Filter} that performs HTTP basic authentication based on API token.
21 *
22 * <p>
23 * Normally the filter chain would also contain another filter that handles BASIC
24 * auth with the real password. Care must be taken to ensure that this doesn't
25 * interfere with the other.
26 *
27 * @author Kohsuke Kawaguchi
28 */
29 public class ApiTokenFilter implements Filter {
30 public void init(FilterConfig filterConfig) throws ServletException {
31 }
32
33 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
34 HttpServletRequest req = (HttpServletRequest) request;
35 HttpServletResponse rsp = (HttpServletResponse) response;
36 String authorization = req.getHeader("Authorization");
37
38 if (authorization!=null) {
39 // authenticate the user
40 String uidpassword = Scrambler.descramble(authorization.substring(6));
41 int idx = uidpassword.indexOf(':');
42 if (idx >= 0) {
43 String username = uidpassword.substring(0, idx);
44 String password = uidpassword.substring(idx+1);
45
46 // attempt to authenticate as API token
47 User u = User.get(username);
48 ApiTokenProperty t = u.getProperty(ApiTokenProperty.class);
49 if (t!=null && t.matchesPassword(password)) {
50 // even if we fail to match the password, we aren't rejecting it.
51 // as the user might be passing in a real password.
52 SecurityContext oldContext = ACL.impersonate(u.impersonate());
53 try {
54 request.setAttribute(ApiTokenProperty.class.getName(), u);
55 chain.doFilter(request,response);
56 return;
57 } finally {
58 SecurityContextHolder.setContext(oldContext);
59 }
60 }
61 }
62 }
63
64 chain.doFilter(request,response);
65 }
66
67 public void destroy() {
68 }
69 }
70