Copy from http://blog.csdn.net/sun_t89/article/details/51916834
@SpringBootApplication
public class Springrestapplication {
public static void Main (string[] args) {
Springapplication.run (Springrestapplication.class, args);
}
@Bean
Public Filterregistrationbean Filterregistrationbean () {
Filterregistrationbean Registrationbean = new Filterregistrationbean ();
Httpbasicauthorizeattribute httpbasicfilter = new Httpbasicauthorizeattribute ();
Registrationbean.setfilter (Httpbasicfilter);
list<string> urlpatterns = new arraylist<string> ();
Urlpatterns.add ("/user/*");
Registrationbean.seturlpatterns (Urlpatterns);
return Registrationbean;
}
}
public class Httpbasicauthorizeattribute implements filter{
private static String Name = "Test";
private static String Password = "Test";
@Override
public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain)
Throws IOException, Servletexception {
TODO auto-generated Method Stub
Resultstatuscode Resultstatuscode = checkhttpbasicauthorize (request);
if (resultstatuscode! = Resultstatuscode.ok)
{
HttpServletResponse HttpResponse = (httpservletresponse) response;
Httpresponse.setcharacterencoding ("UTF-8");
Httpresponse.setcontenttype ("Application/json; Charset=utf-8 ");
Httpresponse.setstatus (httpservletresponse.sc_unauthorized);
Objectmapper mapper = new Objectmapper ();
resultmsg resultmsg = new Resultmsg (ResultStatusCode.PERMISSION_DENIED.getErrcode (), ResultStatusCode.PERMISSION_DENIED.getErrmsg (), NULL);
Httpresponse.getwriter (). Write ( Mapper.writevalueasstring (resultmsg));
return;
}
Else
{
Chain.dofilter (request, response);
}
}
@Override
public void init (Filterconfig arg0) throws Servletexception {
TODO auto-generated Method Stub
}
@Override
public void Destroy () {
TODO auto-generated Method Stub
}
Private Resultstatuscode Checkhttpbasicauthorize (ServletRequest request)
{
Try
{
HttpServletRequest HttpRequest = (httpservletrequest) request;
String auth = httprequest.getheader ("Authorization");
if ((auth! = null) && (Auth.length () > 6))
{
String headstr = auth.substring (0, 5). toLowerCase ();
if (Headstr.compareto ("basic") = = 0)
{
Auth = auth.substring (6, Auth.length ());
String Decodedauth = getFromBASE64 (auth);
if (Decodedauth! = null)
{
string[] Userarray = Decodedauth.split (":");
if (Userarray! = null && userarray.length = = 2)
{
if (Userarray[0].compareto (Name) = = 0
&& Userarray[1].compareto (Password) = = 0)
{
return Resultstatuscode.ok;
}
}
}
}
}
return resultstatuscode.permission_denied;
}
catch (Exception ex)
{
return resultstatuscode.permission_denied;
}
}
private String getFromBASE64 (string s) {
if (s = = null)
return null;
Base64decoder decoder = new Base64decoder ();
try {
Byte[] B = Decoder.decodebuffer (s);
return new String (b);
} catch (Exception e) {
return null;
}
}
Spring boot-filter for simple HTTP Basic authentication