简体   繁体   中英

How to Handle Basic Authentication in java

I get a REST url which has basic auth information passed in as headers in Basic username@domain:password format which is base64 encoded. In my java code, how do I actually validate the credentials. I deploy an EAR on Websphere server. Should I decode the base 64 format header and compare the credentials with the ones from the jndi variables?
(I guess I am confused with the actual flow of basic Auth itself.)
Thanks

In the web.xml you can defined patterns how the server should validate these credentials:

To handle basic authentication you have to configure this:

<login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>default</realm-name>
</login-config>

Now you can secure your services with security contraints eg:

<security-constraint>
  <display-name>excluded</display-name>
  <web-resource-collection>
    <web-resource-name>No Access</web-resource-name>
    <url-pattern>/rest/*</url-pattern>
    <http-method>DELETE</http-method>
    <http-method>PUT</http-method>
    <http-method>HEAD</http-method>
    <http-method>OPTIONS</http-method>
    <http-method>TRACE</http-method>
    <http-method>GET</http-method>
    <http-method>POST</http-method>
  </web-resource-collection>
  <auth-constraint />
  <user-data-constraint>
    <transport-guarantee>NONE</transport-guarantee>
  </user-data-constraint>
</security-constraint>

For more details read the following tutorial: http://java.dzone.com/articles/understanding-web-security

The Java EE tutorial also talks about security: http://docs.oracle.com/javaee/6/tutorial/doc/bncas.html

You could also implement a ServletRequestListener and get the Basic Header from the request. More details can be found here:

http://www.journaldev.com/1945/servlet-listener-example-servletcontextlistener-httpsessionlistener-and-servletrequestlistener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM