List of usage examples for org.springframework.http HttpHeaders WWW_AUTHENTICATE
String WWW_AUTHENTICATE
To view the source code for org.springframework.http HttpHeaders WWW_AUTHENTICATE.
Click Source Link
From source file:com.snv.guard.AuthenticationServiceTest.java
@Test public void should_return_user_with_security_information_when_authenticate() throws HmacException { when(this.authenticationManager.authenticate(Matchers.any(UsernamePasswordAuthenticationToken.class))) .thenReturn(this.authentication); when(this.userService.byLogin(Matchers.any(Credential.class))).thenReturn(this.user); HttpServletResponse response = new MockHttpServletResponse(); User actual = this.authenticationService.authenticate(this.credential, response); assertEquals(this.user, actual); assertTrue(response.getHeader(HmacUtils.X_SECRET) != null); assertEquals(actual.getPublicSecret(), response.getHeader(HmacUtils.X_SECRET)); assertTrue(response.getHeader(HttpHeaders.WWW_AUTHENTICATE) != null); assertEquals(response.getHeader(HttpHeaders.WWW_AUTHENTICATE), HmacUtils.HMAC_SHA_256); assertTrue(response.getHeader(CSRF_CLAIM_HEADER) != null); }
From source file:com.devicehive.application.security.WebSecurityConfig.java
@Bean public AuthenticationEntryPoint unauthorizedEntryPoint() { return (request, response, authException) -> { Optional<String> authHeader = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION)); if (authHeader.isPresent() && authHeader.get().startsWith(Constants.TOKEN_SCHEME)) { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Messages.OAUTH_REALM); } else {//from w w w . j a v a 2 s . c om response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Messages.BASIC_REALM); } response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getOutputStream().println(gson .toJson(new ErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()))); }; }
From source file:org.mitreid.multiparty.web.ClientController.java
@RequestMapping(value = "/fetch", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_FORM_URLENCODED_VALUE) public String fetch(@RequestParam("resource") String resource, Model m, HttpSession session) { // get the access token if we have one String accessTokenValue = acccessTokenService.getAccessToken(resource); // send our request to the resource HttpHeaders headers = new HttpHeaders(); if (!Strings.isNullOrEmpty(accessTokenValue)) { headers.add("Authorization", "Bearer " + accessTokenValue); }//from w w w. ja va 2s .c om @SuppressWarnings("rawtypes") HttpEntity request = new HttpEntity<>(headers); ResponseEntity<String> responseEntity = restTemplate.exchange(resource, HttpMethod.GET, request, String.class); if (responseEntity.getStatusCode().equals(HttpStatus.OK)) { // if we get back data, display it JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject(); m.addAttribute("label", rso.get("label").getAsString()); m.addAttribute("value", rso.get("value").getAsString()); return "home"; } else { // if we get back an error, try to get an access token List<String> authHeaders = responseEntity.getHeaders().get(HttpHeaders.WWW_AUTHENTICATE); // assume there's only one auth header for now String authHeader = Iterators.getOnlyElement(authHeaders.iterator()); // parse the header to get the good bits String authServerUri = null; String ticket = null; Iterable<String> parts = Splitter.on(",").split(authHeader.substring("UMA ".length())); for (String part : parts) { List<String> subparts = Splitter.on("=").splitToList(part.trim()); if (subparts.get(0).equals("as_uri")) { authServerUri = subparts.get(1); // strip quotes authServerUri = authServerUri.substring(1, authServerUri.length() - 1); } else if (subparts.get(0).equals("ticket")) { ticket = subparts.get(1); // strip quotes ticket = ticket.substring(1, ticket.length() - 1); } } // find the AS we need to talk to (maybe discover) MultipartyServerConfiguration server = serverConfig.getServerConfiguration(authServerUri); // find the client configuration (maybe register) RegisteredClient client = clientConfig.getClientConfiguration(server); HttpHeaders tokenHeaders = new HttpHeaders(); tokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // send request to the token endpoint MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("client_id", client.getClientId()); params.add("client_secret", client.getClientSecret()); params.add("grant_type", "urn:ietf:params:oauth:grant_type:multiparty-delegation"); params.add("ticket", ticket); //params.add("scope", "read write"); HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(params, tokenHeaders); ResponseEntity<String> tokenResponse = restTemplate.postForEntity(server.getTokenEndpointUri(), tokenRequest, String.class); JsonObject o = parser.parse(tokenResponse.getBody()).getAsJsonObject(); if (o.has("error")) { if (o.get("error").getAsString().equals("need_info")) { // if we get need info, redirect JsonObject details = o.get("error_details").getAsJsonObject(); // this is the URL to send the user to String claimsEndpoint = details.get("requesting_party_claims_endpoint").getAsString(); String newTicket = details.get("ticket").getAsString(); // set a state value for our return String state = UUID.randomUUID().toString(); session.setAttribute(STATE_SESSION_VAR, state); // save bits about the request we were trying to make session.setAttribute(RESOURCE_SESSION_VAR, resource); session.setAttribute(AUTHSERVERURI_SESSION_VAR, authServerUri); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(claimsEndpoint) .queryParam("client_id", client.getClientId()).queryParam("ticket", newTicket) .queryParam("claims_redirect_uri", client.getClaimsRedirectUris().iterator().next()) // get the first one and punt .queryParam("state", state); return "redirect:" + builder.build(); } else { // it's an error we don't know how to deal with, give up logger.error("Unknown error from token endpoint: " + o.get("error").getAsString()); return "home"; } } else { // if we get an access token, try it again accessTokenValue = o.get("access_token").getAsString(); acccessTokenService.saveAccesstoken(resource, accessTokenValue); headers = new HttpHeaders(); if (!Strings.isNullOrEmpty(accessTokenValue)) { headers.add("Authorization", "Bearer " + accessTokenValue); } request = new HttpEntity<>(headers); responseEntity = restTemplate.exchange(resource, HttpMethod.GET, request, String.class); if (responseEntity.getStatusCode().equals(HttpStatus.OK)) { // if we get back data, display it JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject(); m.addAttribute("label", rso.get("label").getAsString()); m.addAttribute("value", rso.get("value").getAsString()); return "home"; } else { logger.error("Unable to get a token"); return "home"; } } } }
From source file:org.mitreid.multiparty.web.ResourceController.java
@RequestMapping(value = "/api/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody// w w w .jav a 2 s. c om public Resource getResource(@PathVariable("id") String rsId, @RequestHeader(value = "Authorization", required = false) String authorization, HttpServletResponse response) throws JsonIOException, IOException { // load the resource from the ID Resource res = resourceService.getById(rsId); if (res == null) { // no resource with that ID, return a 404 response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } // get the resource set associated with the resource SharedResourceSet resourceSet = resourceService.getSharedResourceSetForResource(res); if (resourceSet == null) { // not shared yet, return a 404 response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } // load the server configuration based on the issuer from the resource set MultipartyServerConfiguration server = serverConfig.getServerConfiguration(resourceSet.getIssuer()); // load client configuration (register if needed) RegisteredClient client = clientConfig.getClientConfiguration(server); // get an access token String protectionAccessTokenValue = acccessTokenService.getAccessToken(server, client); // get a permission ticket for this resource set String ticket = getTicket(resourceSet, server, client, protectionAccessTokenValue); if (Strings.isNullOrEmpty(ticket)) { // couldn't get a ticket for some reason response.addHeader(HttpHeaders.WARNING, "199 - UMA Authorization Server Unreachable"); response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); return null; } // add the issuer and ticket to the response header response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "UMA realm=\"multiparty-resource\", as_uri=\"" + resourceSet.getIssuer() + "\", ticket=\"" + ticket + "\""); // check the request to get the incoming token if (Strings.isNullOrEmpty(authorization) || !authorization.toLowerCase().startsWith("bearer ")) { // no token, return a 401 response.setStatus(HttpStatus.UNAUTHORIZED.value()); return null; } String incomingAccessToken = authorization.substring("bearer ".length()); // introspect/load the token JsonObject introspected = introspectToken(incomingAccessToken, server, client, protectionAccessTokenValue); if (!introspected.get("active").getAsBoolean()) { // token wasn't active, forbidden response.setStatus(HttpStatus.FORBIDDEN.value()); return null; } JsonArray permissions = introspected.get("permissions").getAsJsonArray(); for (JsonElement permission : permissions) { // check to see that the token is for the right resource set String permissionRsid = permission.getAsJsonObject().get("resource_set_id").getAsString(); if (permissionRsid.equals(resourceSet.getRsid())) { // check to see if the token has the right scopes Set<String> scopes = JsonUtils.getAsStringSet(permission.getAsJsonObject(), "permission_scopes"); if (scopes.contains("read")) { // if the token is good enough, return the resource return res; } } } // if we fall down here then we didn't find a workable permission response.setStatus(HttpStatus.FORBIDDEN.value()); return null; }
From source file:net.shibboleth.idp.authn.spnego.impl.SPNEGOAuthnController.java
/** * Send back a Negotiate challenge token. * /*ww w.j a v a 2 s .c om*/ * @param profileRequestContext profile request context * @param httpRequest servlet request * @param httpResponse servlet response * @param base64Token challenge token to send back * * @return a {@link ModelAndView} wrapping the response */ @Nonnull private ModelAndView replyUnauthorizedNegotiate(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final HttpServletRequest httpRequest, @Nonnull final HttpServletResponse httpResponse, @Nonnull final String base64Token) { final StringBuilder authenticateHeader = new StringBuilder("Negotiate"); if (!base64Token.isEmpty()) { authenticateHeader.append(" " + base64Token); } httpResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, authenticateHeader.toString()); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return createModelAndView(profileRequestContext, httpRequest, httpResponse); }