Skip to content

Instantly share code, notes, and snippets.

@kjunine
Created April 30, 2013 07:15
Show Gist options
  • Select an option

  • Save kjunine/5487105 to your computer and use it in GitHub Desktop.

Select an option

Save kjunine/5487105 to your computer and use it in GitHub Desktop.
API Authentication with spring security
@Component
public class ApiAuthenticationEntryPoint implements
AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
@Component
public class ApiAuthenticationFilter extends GenericFilterBean {
@Autowired
private KeyManager keyManager;
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
String header = request.getHeader("Authentication-Key");
boolean authenticated = authenticate(header);
if (!authenticated) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Authentication Failed: Key doesn't exist or is disabled.");
} else {
register(request, header);
chain.doFilter(request, response);
}
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Authentication Failed: " + e.getMessage());
}
}
private boolean authenticate(String header) {
try {
UUID id = UUID.fromString(header);
Key key = keyManager.read(id);
return key != null && key.isEnabled();
} catch (Exception e) {
return false;
}
}
private void register(HttpServletRequest request, String header) {
UUID key = UUID.fromString(header);
request.setAttribute("key", key);
}
}
<sec:http auto-config="false" create-session="never"
use-expressions="true" pattern="/api/**" entry-point-ref="apiAuthenticationEntryPoint">
<sec:custom-filter ref="apiAuthenticationFilter"
position="FORM_LOGIN_FILTER" />
</sec:http>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment