Basic and digest certification for REST API with Spring security (Digest): Basic Certification
1. Server-spring Security Configuration
Package com.pechen.config;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.security.authentication.AuthenticationManager;
Import Org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
Import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Import Org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class Websecurityconfig extends Websecurityconfigureradapter {public final
Static String realm= "My_realm"; @Autowired public void configureglobalsecurity (Authenticationmanagerbuilder auth) throws Exception {Auth.inme Moryauthentication (). Withuser ("admin"). Password ("adMin "). Roles (" ADMIN "). and (). Withuser (" test "). Password (" Test "). Roles (" USER ");
} @Override protected void Configure (Httpsecurity http) throws Exception {http.csrf (). Disable () . Authorizerequests (). Anyrequest (). authenticated (). and (). Httpbasic (). Realmname (REALM). Authentication
EntryPoint (Getbasicauthentrypoint ()); . and (). Sessionmanagement (). Sessioncreationpolicy (sessioncreationpolicy.stateless);//we don ' t need sessions to B
E created. } @Bean Public Custombasicauthenticationentrypoint Getbasicauthentrypoint () {return new Custombasicau
Thenticationentrypoint (); } @Bean Public AuthenticationManager Authenticationmanagerbean () throws Exception {//Altough this s Eems like useless code,//It required to prevend Spring boot auto-configuration return super.authenticat
Ionmanagerbean ();
}
}
Package com.pechen.config;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import org.springframework.security.core.AuthenticationException;
Import Org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; public class Custombasicauthenticationentrypoint extends Basicauthenticationentrypoint {@Override public void Commenc E (final httpservletrequest request, final httpservletresponse response, final authenticationexception authexception) th
Rows IOException, servletexception {response.setstatus (httpservletresponse.sc_unauthorized);
Response.AddHeader ("Www-authenticate", "Basic realm=\" "+ getrealmname () +" \ ");
PrintWriter writer = Response.getwriter ();
Writer.println ("HTTP Status 401:" + authexception.getmessage ()); } @Override public void Afterpropertiesset () throws Exception {Setrealmname (Websecurityconfig.realm);
Super.afterpropertiesset ();
}
}
2. Server-rest API
Package com.pechen.rest;
Import Java.util.Map;
Import Org.springframework.web.bind.annotation.RequestHeader;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.springframework.web.bind.annotation.RestController;
/**
* Authentication Service.
*
/@RestController @RequestMapping (Path = "/") public
class Restservice {
@RequestMapping (path = "/ Login ", method = requestmethod.get) public
String Login (@RequestHeader map<string, object> headers) {
Return "Login success ...";}
3. Client-rest template (plus authorization's head)
Package com.pechen.test;
Import java.util.Base64;
Import Org.junit.Test;
Import org.springframework.http.HttpEntity;
Import Org.springframework.http.HttpHeaders;
Import Org.springframework.http.HttpMethod;
Import org.springframework.http.ResponseEntity;
Import Org.springframework.web.client.RestTemplate;
public class Authservicetest {private Httpheaders getheaders () {String plaincredentials= "admin:admin";
String base64credentials = Base64.getencoder (). Encodetostring (Plaincredentials.getbytes ());
Httpheaders headers = new Httpheaders ();
Headers.add ("Authorization", "Basic" + base64credentials);
return headers;
} @Test public void Testlogin () {resttemplate resttemplate = new Resttemplate ();
httpentity<string> request = new httpentity<string> (Getheaders ());
responseentity<string> response = Resttemplate.exchange ("Http://localhost:8080/login", Httpmethod.get,
request, String.class);
System.out.println (Response.getbody ());
}
}
Digest Certification
1. Server-spring Security Configuration
Package com.pechen.config;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.security.authentication.AuthenticationManager;
Import Org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
Import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Import Org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
Import Org.springframework.security.config.http.SessionCreationPolicy;
Import Org.springframework.security.core.userdetails.UserDetailsService;
Import Org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
@Configuration @EnableWebSecurity public class Websecurityconfig extends Websecurityconfigureradapter { Public final static String realm= "My_realm"; @Autowired public void configureglobalsecurity (Authenticationmanagerbuilder auth) throws Exception {Auth.inme Moryauthentication (). Withuser ("admin"). Password ("admin"). Roles ("admin"). and (). Withuser ("test"). Password ("test")
). Roles ("USER"); } @Override protected void Configure (Httpsecurity http) throws Exception {http.csrf (). Disable (). Autho Rizerequests (). Anyrequest (). authenticated (). and (). Sessionmanagement (). Sessioncreationpolicy ( sessioncreationpolicy.stateless). and (). ExceptionHandling (). Authenticationentrypoint (Getdigestentrypoint ()).
(). addfilter (Getdigestauthenticationfilter (Getdigestentrypoint ())); } @Bean Public Mydigestauthenticationentrypoint getdigestentrypoint () {Mydigestauthenticationentrypoint digestAu
Thenticationentrypoint = new Mydigestauthenticationentrypoint ();
Digestauthenticationentrypoint.setkey ("MyKey"); DigestauthenticationentRypoint.setnoncevalidityseconds (120);
Digestauthenticationentrypoint.setrealmname (REALM);
return digestauthenticationentrypoint; } public Digestauthenticationfilter Getdigestauthenticationfilter (mydigestauthenticationentrypoint Digestauthenticationentrypoint) throws Exception {Digestauthenticationfilter digestauthenticationfilter = new
Digestauthenticationfilter ();
Digestauthenticationfilter.setauthenticationentrypoint (Digestauthenticationentrypoint);
Digestauthenticationfilter.setuserdetailsservice (Userdetailsservicebean ());
return digestauthenticationfilter; } @Override @Bean public Userdetailsservice Userdetailsservicebean () throws Exception {return Super.userdetailsser
Vicebean ();
}
}
Package com.pechen.config;
Import Org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint;
public class Mydigestauthenticationentrypoint extends Digestauthenticationentrypoint {
@Override public
Void Afterpropertiesset () throws exception{
Super.afterpropertiesset ();
Setrealmname (Websecurityconfig.realm);
}
}
2. Server-rest API Ibid.
3. Client-Configure rest template to use Digest authentication
Package com.pechen.rest;
Import Org.apache.http.auth.AuthScope;
Import Org.apache.http.auth.UsernamePasswordCredentials;
Import Org.apache.http.client.CredentialsProvider;
Import Org.apache.http.impl.client.BasicCredentialsProvider;
Import org.apache.http.impl.client.CloseableHttpClient;
Import Org.apache.http.impl.client.HttpClientBuilder;
Import Org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
Import Org.springframework.web.client.RestTemplate; public class Resttempleteconfig {public Resttemplate getresttemplate () {closeablehttpclient client = Httpclientbuild
Er.create (). Setdefaultcredentialsprovider (Provider ()). Usesystemproperties (). build ();
Httpcomponentsclienthttprequestfactory requestfactory = new Httpcomponentsclienthttprequestfactorydigestauth (
Client);
return new Resttemplate (requestfactory);
} private Credentialsprovider Provider () {Credentialsprovider Provider = new Basiccredentialsprovider (); Usernamepasswordcredentials CREdentials = new Usernamepasswordcredentials ("admin", "admin");
Provider.setcredentials (authscope.any, credentials);
return provider;
}
}
Package com.pechen.rest;
Import Java.net.URI;
Import Org.apache.http.HttpHost;
Import Org.apache.http.client.AuthCache;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.protocol.ClientContext;
Import Org.apache.http.impl.auth.DigestScheme;
Import Org.apache.http.impl.client.BasicAuthCache;
Import Org.apache.http.protocol.BasicHttpContext;
Import Org.apache.http.protocol.HttpContext;
Import Org.springframework.http.HttpMethod;
Import Org.springframework.http.client.HttpComponentsClientHttpRequestFactory; public class Httpcomponentsclienthttprequestfactorydigestauth extends Httpcomponentsclienthttprequestfactory {Publ
IC Httpcomponentsclienthttprequestfactorydigestauth (HttpClient client) {super (client); } @Override protected HttpContext createhttpcontext (HttpMethod HttpMethod, Uri Uri) {return CREATEHTTPC
Ontext (URI); } private HttpContext Createhttpcontext (Uri uri) {//Create Authcache instance AutHcache Authcache = new Basicauthcache (); Generate DIGEST Scheme object, initialize it and add it to the local auth cache digestscheme Digestauth = new D
Igestscheme ();
If we already know the realm name Digestauth.overrideparamter ("Realm", "Myrealm");
Httphost targethost = new Httphost (Uri.gethost (), Uri.getport ());
Authcache.put (Targethost, Digestauth);
Add Authcache to the execution context basichttpcontext Localcontext = new Basichttpcontext ();
Localcontext.setattribute (Clientcontext.auth_cache, Authcache);
return localcontext;
}
}
4. Use rest template to send requests
Package com.pechen.test;
Import Org.junit.Test;
Import Org.springframework.http.HttpMethod;
Import org.springframework.http.ResponseEntity;
Import org.springframework.web.client.RestTemplate;
Import Jdk.nashorn.internal.ir.annotations.Ignore;
public class Restclient {
@Test public
void Whensecuredrestapiisconsumed_then200ok () {
resttemplate Resttemplate = new Resttempleteconfig (). Getresttemplate ();
String uri = "Http://localhost:8080/login";
responseentity<string> entity = Resttemplate.exchange (URI, httpmethod.get, NULL, string.class);
System.out.println (Entity.getstatuscode ());
System.out.println (Entity.getbody ());
}
}