1 package com.pentila.basic;
3 import java.io.IOException;
4 import java.io.UnsupportedEncodingException;
6 import javax.servlet.Filter;
7 import javax.servlet.FilterChain;
8 import javax.servlet.FilterConfig;
9 import javax.servlet.ServletException;
10 import javax.servlet.ServletRequest;
11 import javax.servlet.ServletResponse;
12 import javax.servlet.http.HttpServletRequest;
15 import org.apache.commons.codec.binary.Base64;
18 import org.springframework.security.core.context.SecurityContextHolder;
19 import org.springframework.security.core.userdetails.UsernameNotFoundException;
23 public class AuthFilter implements Filter {
27 public void destroy() {
28 // TODO Auto-generated method stub
32 public void doFilter(ServletRequest request, ServletResponse response,
33 FilterChain chain) throws IOException, ServletException {
35 loginToThread((HttpServletRequest) request);
38 chain.doFilter(request, response);
40 } catch (IOException e) {
41 // TODO Auto-generated catch block
43 } catch (ServletException e) {
44 // TODO Auto-generated catch block
46 } catch (Exception e){
49 logoutFromThread((HttpServletRequest) request);
52 private static void logoutFromThread(HttpServletRequest request) {
57 private static void loginToThread(HttpServletRequest request) {
58 System.out.println("debut");
59 String basicAuth = request.getHeader("login");
60 System.out.println(basicAuth);
63 if (basicAuth == null){
64 basicAuth = request.getParameter("login");
67 System.out.println("ECHO 1 : " + basicAuth);
72 if (basicAuth != null){
74 System.out.println("ECHO 2: " + basicAuth);
75 login = processBasicAuthToken(basicAuth);
77 System.out.println(login);
79 System.out.println("ECHO 3 : else");
80 login = request.getHeader("login");
81 System.out.println(login);
83 login = request.getParameter("login");
84 System.out.println("ECHO 4 : login >>> "+ login);
92 System.out.println("ECHO 6 ADD TO SECURITY CONTEXT ");
94 FakeAuthentication fa = new FakeAuthentication(login);
96 SecurityContextHolder.getContext().setAuthentication(fa);
99 System.out.println("ECHO 5 excpetion >>> ");
100 throw new UsernameNotFoundException("Failed !");
108 private static String processBasicAuthToken(String basicAuth) {
109 if (basicAuth != null && basicAuth.startsWith("Basic ")) {
112 base64Token = basicAuth.substring(6).getBytes("UTF-8");
115 String token = new String(Base64.decodeBase64(base64Token));
117 String username = "";
119 String password = "";
121 int delim = token.indexOf(":");
125 username = token.substring(0, delim);
127 password = token.substring(delim + 1);
129 System.out.println("username " + username + " / " + password);
133 } catch (UnsupportedEncodingException e) {
134 // TODO Auto-generated catch block
143 public void init(FilterConfig arg0) throws ServletException {
144 // TODO Auto-generated method stub