Ldap Auth as Rest Controller - spring

I have configured a remote Ldap server, I have a frontend and the desired behavior is: When the user fills the login form in frontend, I want to send credentials to backend via a controller then backend should perform a lookup to my ldap server and return a response to identify the user like his id and null if user is not found.
I am having a hard time about wrapping my head around the concept and all examples are either using a local ldap or redirecting to login form on backend. I do not want the login form on backend or secure some endpoints.

This is what I am doing in my project:
in application.properties file
server,protocol=http://
server.host.name=
server.ip=
server.port=
server.url=
Then from RESTController I am calling this service:
#Service
public class ldapService
{
#Value("${ldap.server.protocol}")
private String LDAP_SERVER_PROTOCOL;
#Value("${ldap.server.ip}")
private String LDAP_SERVER_IP;
#Value("${ldap.server.port}")
private int LDAP_SERVER_PORT;
#Value("${ldap.service.url}")
private String LDAP_SERVICE_URL;
public String authenticate(LoginDto loginDto){
UserCredentials userCredentials = new UserCredentials(loginDto.getUserName(), loginDto.getPassword());
RestTemplate restTemplate = new RestTemplate();
HttpEntity<UserCredentials> httpEntity = new HttpEntity<UserCredentials>(userCredentials);
final String FINAL_URL = LDAP_SERVER_PROTOCOL + LDAP_SERVER_IP + LDAP_SERVER_PORT + LDAP_SERVICE_URL;
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(FINAL_URL);
ResponseEntity<ResponseDto> exchange = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
httpEntity, ResponseDto.class);
HttpStatus statusCode = exchange.getStatusCode();
ResponseDto responseDto = exchange.getBody();
// check if response OK and is user validated.
if (statusCode == HttpStatus.OK)
{
//switch according to HttpStatus
}

Related

OAuth2.0 authorization spring boot web application flow

i am using java library client for web application authentication, i produce authorization url using client secret and client id,also i provided a redirect url within google api console,but i don't know if it is necessary for me to create this server to receive refresh token?
i mean in production i should provide a separate server to receive the refresh token?(redirect url comes to this server)
the main problem is user should paste the produced url on browser by himself but i want to open browser authmaticly , the second one is about reciving the refresh token i am not sure about creating another server to recieve refreshcode and i can't use service accounts i am going with web flow authentication.
UserAuthorizer userAuthorizer =
UserAuthorizer.newBuilder()
.setClientId(ClientId.of(clientId, clientSecret))
.setScopes(SCOPES)
.setCallbackUri(URI.create(OAUTH2_CALLBACK_URL_CONFIGURED_AT_GOOGLE_CONSOLE))
.build();
baseUri = URI.create("http://localhost:" + simpleCallbackServer.getLocalPort());
System.out.printf(
"Paste this url in your browser:%n%s%n",
userAuthorizer.getAuthorizationUrl(loginEmailAddressHint, state, baseUri));
and this is local server to receive refresh token:
private static class SimpleCallbackServer extends ServerSocket {
private AuthorizationResponse authorizationResponse;
SimpleCallbackServer() throws IOException {
// Passes a port # of zero so that a port will be automatically allocated.
super(0);
}
/**
* Blocks until a connection is made to this server. After this method completes, the
* authorizationResponse of this server will be set, provided the request line is in the
* expected format.
*/
#Override
public Socket accept() throws IOException {
Socket socket = super.accept();
}
}
for those who struggling to get authorized using google oauth2.0 with spring boot
you cant redirect user to authorization url(which google authorization server gives to using your client id and client secret) use a controller to redirect user:
#GetMapping(value = "/redirect-user")
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
String url=gs.createUserAuthorizationUrl();
URI authorizationUrl = new URI(url);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(authorizationUrl);
return new ResponseEntity<>(httpHeaders, HttpStatus.FOUND);
}
at service layer createUserAuthorizationUrl() method is like below:
public String createUserAuthorizationUrl() {
clientId = "client-id";
clientSecret = "client-secret-code";
userAuthorizer =
UserAuthorizer.newBuilder()
.setClientId(ClientId.of(clientId, clientSecret))
.setScopes(SCOPES)
.setCallbackUri(URI.create("/oauth2callback"))
.build();
baseUri = URI.create("your-app-redirect-url-configured-at-google-console" + "your-spring-boot-server-port"); //giving redirect url
String redirectURL = userAuthorizer.getAuthorizationUrl(loginEmailAddressHint, state, baseUri).toString();
return redirectURL;
}
and let's create a controller to support the get request comming from google authorization server with an code. we are going to use that code to get access token from google.i get state and code by #RequestParam
and i also want to redirect user to my application.
#GetMapping(value = "/oauth2callback")
public ResponseEntity<Object> proceedeTOServer(#RequestParam String state,
#RequestParam String code) throws URISyntaxException {
String url="my-application-url-to-redirect-user";
URI dashboardURL = new URI(url);
HttpHeaders httpHeaders=new HttpHeaders();
httpHeaders.setLocation(dashboardURL);
gs.getCode(state,code);
return new ResponseEntity<>(httpHeaders,HttpStatus.FOUND);
}
and in getCode(code) in service layer i am going to send to code and receive the refresh token or access token:
UserCredentials userCredentials =userAuthorizer.getCredentialsFromCode(code, "your-app-redirect-url-configured-at-google-console" + "your-spring-boot-server-port");

Service that checks if token hasnt expired

so I have a authentication bean which provides access tokens from client credentials.
public class AuthServiceBean {
#Value("${some.url}")
private String someUrl;
#Value("${some.clientId}")
private String someClientId;
#Value("${some.secret}")
private String someSecret;
#Value("${some.username}")
private String someUsername;
#Value("${some.password}")
private String somePassword;
public AuthInfo getPrevAuth() {
return prevAuth;
}
public void setPrevAuth(AuthInfo prevAuth) {
this.prevAuth = prevAuth;
}
private AuthInfo prevAuth;
public AuthInfo getAuthInfo() throws IOException {
if (this.prevAuth != null && this.prevAuth.isNotExpired()) {
return this.prevAuth;
}
return this.Authenticate();
}
private AuthInfo Authenticate() throws IOException {
final String url = this.someUrl + "/api/oauth/v1/token";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
String clientIdSecret = this.someClientId +":"+ this.someSecret;
String authString = Base64.getEncoder().encodeToString(clientIdSecret.getBytes());
headers.add("Authorization", "Basic " + authString);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", this.someUsername);
map.add("password", this.somePassword);
map.add("grant_type", "password");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<?> response = restTemplate.postForEntity(url, request, String.class);
String bodyString = response.getBody().toString();
ObjectMapper mapper = new ObjectMapper();
try {
AuthInfo authInfo = mapper.readValue(bodyString, AuthInfo.class);
this.prevAuth = authInfo;
return this.prevAuth;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
And now how do I need to create service which checks if that access token valid if it hasn't expired and how to use refresh token. When access token expires I could ask new token with refresh token? Would be good to get any examples.
First of all, As I see in your code, you are using password grant type, not client credentials, and because of this, you pass also user credentials (username and password) in addition to the client credentials, client id and client secret.
Anyway, the reason because all the examples you found to check expiration are using jwt tokens is because these tokens have this information coded in the token itself, so you can parse it using some kind of library like Nimbus Jose and get the "exp" claim and check directly if that date is before or after the actual date.
If the token is an opaque one (not jwt). You don't have any way to check the expiration without call the server who issued that token. Normally the server (an oauth2 server) provides and endpoint called introspect in which you pass a token and it responds indicating if this token is valid or is not, because it has expired or it is revoked etc..

feign client - retrieving jwt token from a service and setting it automatically in feign client

I'm using feign client to call other services.
Service A need to contact Service B and has to be authenticated via authentication service.
If I wasn't using feign, I would just use resttemplate calling first the authentication service.. get the token, add it to the header of the msg I want to send to service B.
Is it possible to configure to feign an endpoint that from there he gets the token so it would be done automatically?
Considering you have prepeared JWT authroization and authentication in the authentication service, i can give my example like this:
First feign client using OpenFeign (the latest feign implementation of spring)
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
// Must give a url to NOT use load balancer (we have a gateway)
// Otherwise it will throw "did you forget load balancer?" error
#FeignClient(url = "http://localhost:<port>/", name = "UserClient")
public interface UserClient
{
#PostMapping(path = "login", consumes = "application/json")
ResponseEntity<String> login(#RequestBody String user);
#GetMapping(path = "hello")
ResponseEntity<String> sayHello();
}
Then get the jwt token like this: (This code can be in some mvc project)
String username = someuser
String password = somepassword
// I wasn't able to create a json but the below data would work with spring security
String user = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
ResponseEntity<String> responseEntity = userClient.login(user);
// your token could be like "<username> - <token>" kind of structure
String token = responseEntity.getBody();
Then make an authenticated request with openfeign, this code can be in mvc project or something
// If you put the token in session
String bearer = (String) req.getSession().getAttribute("Bearer");
UserClient helloClient = Feign.builder().client(new Client.Default((SSLSocketFactory) SSLSocketFactory.getDefault(), null)).contract(new SpringMvcContract()).requestInterceptor(new RequestInterceptor()
{
#Override
public void apply(RequestTemplate template)
{
System.err.println("This is adding jwt header to resttemplate of the feign");
template.header("Authorization", "Bearer " + bearer);
}
}).decoder(new Decoder()
{
#Override
public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException
{
// If you have returned responseentity, feign client must be able to understand it
return new ResponseEntity<>(response.body().toString(), HttpStatus.resolve(response.status()));
}
}).target(UserClient.class, "http://localhost:4441/hello/");
// My responsebody is a simple string but it could be anything you want, as long as you have the decoder
String response = helloClient.sayHello().getBody();
Feign clients does not have the ability to dynamically set headers, especially from jwt tokens because those tokens are coming from either another request or in session. That is why i use builder to set a dynamic header. If you use BasicAuthRequestInterceptor, you can create a #Bean of BasicAuthRequestInterceptor and set a static username and password inside it.

Share SPRING_SECURITY_CONTEXT between two applications

I have two different Spring Boot Applications that run on localhost on different ports (8080, 8081) and different configs (application.yml). These apps use SSO with OAuth 2.0 to get authorization token from Authorization Server. I log in to my first application, get authorization and everything works great here. Now I need to share these authentication details with second Spring Boot App (on port 8081) to authorize second app in Authorization Server. Googled and found 2 aproaches: I can try to share HttpSession between two apps (but I think it's redundant) OR HttpSessionSecurityContextRepository as SecurityContextRepository which seems more convenient. The problem here is that I can't manage to do so and I'm still not sure that it's a good idea to share Security Context between 2 apps.
What I tried for now:
Share authorization token from first app via headers in GET request (custom-built in accordance with specification for requests for Authorization Server), but it didn't work - second app doesn't take in mind this token.
Share authorized cookie from first app to second, but it didn't work, too.
I can't do authorization through Authorization Server on second app because it may be not a Spring Boot App with #Controller but any other app without HTML forms, so I need to authorize on first app (with UI), get all the data which is needed to perform authorized requests and pass it to second app (third, fourth...) so they will be able to do authorized requests too.
Thanks in advance!
I presume that your authorization/resource server is external application.And you can login successfully with your first application so flow is working.You have two client application with own client_id, client_secret and etc. parameters.If these parameters are different then authorization/resource server will return different bareer token and sessionid cookie for first and second client application.Otherwise you need to authorize both of them in authorization/resource server.
I would offer when user do login to first app then in background you do login also for second application.
For automatically authorizing second application you can try to do oauth2 login flow manually for second application with own parameters when after successful first application login and send cookies to frontend which you got from oauth2 login.
For manual oauth2 login you can try below code:
private Cookie oauth2Login(String username, String password, String clientId, String clientSecret) {
try {
String oauthHost = InetAddress.getByName(OAUTH_HOST).getHostAddress();
HttpHeaders headers = new HttpHeaders();
RestTemplate restTemplate = new RestTemplate();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
// Basic Auth
String plainCreds = clientId + ":" + clientSecret;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = org.apache.commons.net.util.Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
headers.add("Authorization", "Basic " + base64Creds);
// form param
map.add("username", username);
map.add("password", password);
map.add("grant_type", GRANT_TYPE);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
headers);
// CALLING TOKEN URL
OauthTokenRespone res = null;
try {
res = restTemplate.postForObject(OAUTH_HOST, request,
OauthTokenRespone.class);
} catch (Exception ex) {
ex.printStackTrace();
}
Optional<OauthTokenRespone> optRes = Optional.ofNullable(res);
String accessToken = optRes.orElseGet(() -> new OauthTokenRespone("", "", "", "", "", ""))
.getAccess_token();
// CALLING RESOURCE
headers.clear();
map.clear();
headers.setContentType(MediaType.APPLICATION_JSON);
map.add("access_token", accessToken);
request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
Cookie oauthCookie = null;
if (accessToken.length() > 0) {
HttpEntity<String> response = restTemplate.exchange(
OAUTH_RESOURCE_URL.replace(OAUTH_HOST, oauthHost) + "?access_token=" + accessToken,
HttpMethod.POST, request, String.class);
String cookie = Optional.ofNullable(response.getHeaders().get("Set-Cookie"))
.orElseGet(() -> Arrays.asList(new String(""))).get(0);
if (cookie.length() > 0) {
String[] c = cookie.split(";")[0].split("=");
oauthCookie = new Cookie(c[0], c[1]);
oauthCookie.setHttpOnly(true);
}
}
return Optional.ofNullable(oauthCookie).orElseGet(() -> new Cookie("Ops", ""));
} catch (Throwable t) {
return new Cookie("Ops", "");
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class OauthTokenRespone {
private String access_token;
private String token_type;
private String refresh_token;
private String expires_in;
private String scope;
private String organization;
// getter and setter
}
And call this method after first app login as follows :
Cookie oauthCookie = oauth2Login(authenticationRequest.getUsername(), authenticationRequest.getPassword(),
CLIENT_ID, CLIENT_SECRET);
After getting cookie you need change its name (for example JSESSIONID-SECOND) because same cookies will override each other and also need to change its domain path to second app domain.
response.addCookie(oauthCookie);
Last you need add cookie to response (it is HttpServletResponse reference).
Hope it helps!

Spring Social Reddit Extension - OAuth 2 Access_token retrieval. 401 Error

I am trying to create an extension for Reddit's Api. Reddit follows OAuth 2 for obtaining an access_token. I am using springs RestTemplate to make all POST requests to Reddit. I am able to successfully complete the first stage according to the documentation. The user is redirected to Reddit where he/she allows my application, Reddit then redirects me back to my application with a code. However, the second stage doesn't seem to work. I must use that code to make another post request to :
https://ssl.reddit.com/api/v1/access_token
Here is my attempt for obtaining an AccessGrant (SpringSocial wrapper for accesstoken sent back from Reddit). Spring Social requires you to extend OAuth2Template and implement the authentication process from there. In a typical spring application, a controller will use a helper to make a call to RedditOAuth2Template.exchangeForAccess and save the returned AccessGrant into a database.
According to the Reddit API Documentaiton a 401 response occurs due to a lack of client credentials via HTTP basic Auth. However, I am doing that in the createHeaders(String username, String password) method.
public class RedditOAuth2Template extends OAuth2Template {
private static final Logger LOG = LogManager.getLogger(RedditOAuth2Template.class);
private String client_id;
private String client_secret;
public RedditOAuth2Template(String clientId, String clientSecret) {
super(clientId, clientSecret, RedditPaths.OAUTH_AUTH_URL, RedditPaths.OAUTH_TOKEN_URL);
this.client_id = clientId;
this.client_secret = clientSecret;
setUseParametersForClientAuthentication(true);
}
#Override
#SuppressWarnings({"unchecked", "rawtypes"})
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
HttpHeaders headers = createHeaders(client_id, client_secret);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set(accessTokenUrl, accessTokenUrl);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(parameters, headers);
ResponseEntity<Map> responseEntity = getRestTemplate().exchange(accessTokenUrl, HttpMethod.POST, requestEntity, Map.class);
Map<String, Object> responseMap = responseEntity.getBody();
return extractAccessGrant(responseMap);
}
/*
Reddit requires client_id and client_secret be
placed via HTTP basic Auth when retrieving the access_token
*/
private HttpHeaders createHeaders(String username, String password) {
String auth = username + ":" + password;
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
HttpHeaders headers = new HttpHeaders();
String authHeader = "Basic " + new String(encodedAuth);
headers.set("Authorization", authHeader);
return headers;
}
private AccessGrant extractAccessGrant(Map<String, Object> result) {
String accessToken = (String) result.get("access_token");
String scope = (String) result.get("scope");
String refreshToken = (String) result.get("refresh_token");
// result.get("expires_in") may be an Integer, so cast it to Number first.
Number expiresInNumber = (Number) result.get("expires_in");
Long expiresIn = (expiresInNumber == null) ? null : expiresInNumber.longValue();
return createAccessGrant(accessToken, scope, refreshToken, expiresIn, result);
}
}
If you're getting a 401 response for that endpoint, you're doing one of a small number of things wrong, all related to sending the client ID & secret as HTTP Basic Authorization:
Not including a properly formatted Authorization header (i.e., Authorization: basic <b64 encoded credentials>)
Not properly base 64 encoding your credentials
Not including a client_id that for a valid OAuth2 client
Not including a semicolon between the client ID and secret
Not including the secret, or including the WRONG secret
You should check each stage of the Basic client auth, and log your output (or use a debugger to inspect it) at each stage to ensure you're not missing anything. You should also inspect the actual HTTP request you generate, and verify that the header is being sent (some HTTP libraries like to take liberties with headers)

Resources