i want to get UserDetails from HttpServletRequest when I have SessionAuthenticationException - mean that session already exist for current use, but get null
My Hadnler is
public class SecurityErrorHandler extends SimpleUrlAuthenticationFailureHandler {
private static final String FORCE_PARAMETER_NAME = "force";
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception)
throws IOException, ServletException {
//if session already exist
if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {
logger.debug("Session already exist");
Principal userPrincipal = request.getUserPrincipal();
}
}
}
Can anyone help me?
There is no easy way. You need to get it from Authorization header
String authHeader = request.getHeader("Authorization");
byte[] base64Token =
header.trim().substring(6).getBytes(StandardCharsets.UTF_8);
byte[] decoded = java.util.Base64.getDecoder().decode(base64Token);
String token = new String(decoded, StandardCharsets.UTF_8);
int delim = token.indexOf(":");
String userName = token.substring(0, delim);
The above code can look hacky but it is actually what spring security BasicAuthenticationConverter does. https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java#L94
Related
Problem:
I would like to get/extract the username/email only from authenticate.getName()... if possible, not by using parsing the string.
authentication.getName() or principal.getName() values:
[username]: org.springframework.security.core.userdetails.User#21463e7a: Username: butitoy#iyotbihagay.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities
In this example, I would like to get only the value of Username which is butitoy#iyotbihagay.com
Solution:
Since I only want to get the username/email (butitoy#iyotbihagay.com), and it is returning the whole principal content/text (above), I replaced the value I set in the subject from the pricipal value... to the email value.. and it works now.
#Override
protected void successfulAuthentication(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain,
Authentication auth) throws IOException, ServletException {
String email = auth.getName();
String principal = auth.getPrincipal().toString();
Date expiration = new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME);
String token = Jwts.builder()
.setSubject(email) //from principal to email
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes())
.compact();
AuthenticatedUser loginUser = new AuthenticatedUser(email);
loginUser.setToken(token);
String jsonUser = Util.objectToJsonResponseAsString(loginUser, "user");
res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
res.setContentType("application/json");
res.setCharacterEncoding(ConstantUtil.DEFAULT_ENCODING);
res.getWriter().write(jsonUser);
}
I can now get the username/email value using different ways like the one you guys are suggesting... even the one I am currently using. I do not need any special parsing now just to get the email value from the Authentication object.
On my previous non RESTful application using Spring... I can easily get the username using Authentication class injected in the controller method parameter.
Controller:
...
public Ticket getBySwertresNo(Authentication authentication, #PathVariable String swertresNo) {
logger.debug("Inside getBySwertresNo: " + swertresNo);
System.out.println("\n[username]: " + authentication.getName() + "\n");
return m_sugalService.getSwertresInfoBySwertresNo(swertresNo);
}
...
Console:
[username]: butitoy#iyotbihagay.com
Now, on my current project... I used a RESTful approach and after successful authentication, I am returning a token which will be used/injected in the request header. I can login using the token... but when I get the value of authentication.getName()... the return is not just the email address but it contains some other information.
Console (REST + JWT):
[username]: org.springframework.security.core.userdetails.User#21463e7a: Username: butitoy#iyotbihagay.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities
I would like to get only the username value which is "butitoy#iyotbihagay.com".
JWT Authentication Filter:
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
#Override
public Authentication attemptAuthentication(HttpServletRequest req,
HttpServletResponse res) throws AuthenticationException {
String username = req.getParameter("username");
String password = req.getParameter("password");
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authenticationManager.authenticate(authenticationToken);
return authentication;
}
#Override
protected void successfulAuthentication(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain,
Authentication auth) throws IOException, ServletException {
String email = auth.getName();
String principal = auth.getPrincipal().toString();
Date expiration = new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME);
String token = Jwts.builder()
.setSubject(principal)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes())
.compact();
AuthenticatedUser loginUser = new AuthenticatedUser(email);
loginUser.setToken(token);
String jsonUser = Util.objectToJsonResponseAsString(loginUser, "user");
res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
res.setContentType("application/json");
res.setCharacterEncoding(ConstantUtil.DEFAULT_ENCODING);
res.getWriter().write(jsonUser);
}
}
JWT Authorization Filter:
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
public JWTAuthorizationFilter(AuthenticationManager authManager) {
super(authManager);
}
#Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
String header = req.getHeader(SecurityConstants.HEADER_STRING);
if (header == null || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
chain.doFilter(req, res);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader(SecurityConstants.HEADER_STRING);
if (token != null) {
// parse the token.
String user = Jwts.parser()
.setSigningKey(SecurityConstants.SECRET.getBytes())
.parseClaimsJws(token.replace(SecurityConstants.TOKEN_PREFIX, ""))
.getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
}
I think you can use authentication.getName and principal.getName in the injected controller argument of type Authentication and Principal:
#Controller
#RequestMapping("/info")
public class GetNameController {
#RequestMapping(value = "/name", method = RequestMethod.GET)
public String getName(Authentication authentication, Principal principal) {
System.out.println(authentication.getName());
System.out.println("-----------------");
System.out.println(principal.getName());
return "";
}
}
could produce
admin
-----------------
admin
It doesn't matter whether you are using token or basic spring security authentication as far as Authentication/Principal object is concerned.
In case of spring security, you can get your current logged in user by
1. Object user = Authentication authentication (as you are already doing)
2.
Object user = SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
In both cases, user will contains the user object you returning from UserDetailsService.loadUserByUsername(...). So using default UserDetailsService you will get spring security's User object which contains basic user information like username, password etc.
So in case if you are using default spring's UserDetailsService, then you can get your current logged in user simply by
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
String username = userDetails.getUsername();
You can use
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println("--------------------------------------------------------------");
JwtUser jwtUser = (JwtUser) auth.getPrincipal();
//Get the username of the logged in user: getPrincipal()
System.out.println("auth.getPrincipal()=>"+jwtUser.getUsername() );
//Get the password of the authenticated user: getCredentials()
System.out.println("auth.getCredentials()=>"+auth.getCredentials());
//Get the assigned roles of the authenticated user: getAuthorities()
System.out.println("auth.getAuthorities()=>"+auth.getAuthorities());
//Get further details of the authenticated user: getDetails()
System.out.println("auth.getDetails()=>"+auth.getDetails());
System.out.println("--------------------------------------------------------------");
Have not seen so far any accepted answer, maybe this will help:
use JwtTokenUtils.debugPrint(); call from below class. For other token payload see what is available inside tokenMap.
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.springframework.security.oauth2.provider.token.AccessTokenConverter.EXP;
public class JwtTokenUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);
private static Format dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static ObjectMapper objectMapper = new ObjectMapper();
public static void debugPrint() {
try {
Map<String, Object> tokenMap = decode(getToken());
logger.debug("JwtTokenUtils:debugPrint jwt:"
+ " user_name {" + tokenMap.get("user_name")
+ "}, expired {" + convertTime((long)tokenMap.get(EXP))
+ "}");
} catch (Exception e) {
logger.error("JwtTokenUtils:debugPrint exception: " + e);
}
}
private static String getToken() {
return getAuthorizationHeader().split(" ")[1];
}
private static String getAuthorizationHeader() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
return request.getHeader("Authorization");
}
private static Map<String, Object> decode(String token) {
try {
Jwt jwt = JwtHelper.decode(token);
String claimsStr = jwt.getClaims();
TypeReference<HashMap<String,Object>> typeRef = new TypeReference<>() {};
return objectMapper.readValue(claimsStr, typeRef);
}
catch (Exception e) {
throw new InvalidTokenException("Cannot convert access token to JSON", e);
}
}
private static String convertTime(long time){
Date date = new Date(time * 1000);
return dateFormat.format(date);
}
}
I have made a user login interface where the user gets authenticated using spring security.
I have made an AuthenticationSuccessHandler which redirects the user to a new page.
I also want to implement a loginController in order to get the name of user logged in as well as displaying error messages for wrong credentials. Here is my Handler code :
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
protected final Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
protected MySimpleUrlAuthenticationSuccessHandler() {
super();
}
#Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
final String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(final Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (final GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
if (isUser) {
return "/static_htm.html";
} else if (isAdmin) {
return "/console.html";
} else {
throw new IllegalStateException();
}
}
And my controller code :
#Controller
public class HelloController {
#RequestMapping(value="/login", method = RequestMethod.GET)
public String printWelcome(ModelMap model, Principal principal ) {
String name = principal.getName();
model.addAttribute("username", name);
model.addAttribute("message", "Spring Security Hello World");
return "static_htm"; //page after successful login
}
#RequestMapping(value="/login", method = RequestMethod.GET)
public String login(ModelMap model) {
return "login"; //login page
}
#RequestMapping(value="/loginfailed", method = RequestMethod.GET)
public String loginerror(ModelMap model) {
//String errormessage = resources.getMessage("login.error", null, null);
model.addAttribute("error", "true");
return "login"; //login page
}
}
The handler works fine but I am not able to get the user name as well as the error message. What should I do to make both the handler and controller work together ?
Any suggestions are greatly appreciated.
From your question I presume you want to get the user name in the login controller.
If not so, feel free to disregard my answer.
You may have gotten it backward actually.
Success handler is somewhat like a custom implementation of "default-target-url".
So it is actually executed after login controller...
When login is successful, and there's no previously requested path (this is implemented by SavedRequestAwareAuthenticationSuccessHandler) then the request will be sent to the "default-target-url".
Or when there's a custom success handler, the success handler will determine the path it goes to.
To implement HMAC authentication I made my own filter, provider and token.
RestSecurityFilter:
public class RestSecurityFilter extends AbstractAuthenticationProcessingFilter {
private final Logger LOG = LoggerFactory.getLogger(RestSecurityFilter.class);
private AuthenticationManager authenticationManager;
public RestSecurityFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
}
public RestSecurityFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
super(requiresAuthenticationRequestMatcher);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
AuthenticationRequestWrapper request = new AuthenticationRequestWrapper(req);
// Get authorization headers
String signature = request.getHeader("Signature");
String principal = request.getHeader("API-Key");
String timestamp = request.getHeader("timestamp");
if ((signature == null) || (principal == null) || (timestamp == null))
unsuccessfulAuthentication(request, response, new BadHMACAuthRequestException("Authentication attempt failed! Request missing mandatory headers."));
// a rest credential is composed by request data to sign and the signature
RestCredentials credentials = new RestCredentials(HMACUtils.calculateContentToSign(request), signature);
// Create an authentication token
return new RestToken(principal, credentials, Long.parseLong(timestamp));
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
LOG.debug("Filter request: " + req.toString());
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
chain.doFilter(request, response);
Authentication authResult;
try {
authResult = attemptAuthentication(request, response);
if (authResult == null)
unsuccessfulAuthentication(request, response, new BadHMACAuthRequestException("Authentication attempt failed !"));
} catch (InternalAuthenticationServiceException failed) {
LOG.error("An internal error occurred while trying to authenticate the user.", failed);
unsuccessfulAuthentication(request, response, failed);
} catch (AuthenticationException failed) {
// Authentication failed
unsuccessfulAuthentication(request, response, failed);
}
}
}
Authentication provider:
#Component
public class RestAuthenticationProvider implements AuthenticationProvider {
private final Logger LOG = LoggerFactory.getLogger(RestAuthenticationProvider.class);
private ApiKeysService apiKeysService;
#Autowired
public void setApiKeysService(ApiKeysService apiKeysService) {
this.apiKeysService = apiKeysService;
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
RestToken restToken = (RestToken) authentication;
// api key (aka username)
String principal = restToken.getPrincipal();
LOG.info("Authenticating api key: '" + principal + "'");
// check request time, 60000 is one minute
long interval = Clock.systemUTC().millis() - restToken.getTimestamp();
if ((interval < 0) && (interval > 60000))
throw new BadHMACAuthRequestException("Auth Failed: old request.");
// hashed blob
RestCredentials credentials = restToken.getCredentials();
// get secret access key from api key
ApiKey apiKey = apiKeysService.getKeyByName(principal).orElseThrow(() -> new NotFoundException("Key not found for: '" + principal + "'"));
String secret = apiKey.getApiKey();
// calculate the hmac of content with secret key
String hmac = HMACUtils.calculateHMAC(secret, credentials.getRequestData());
LOG.debug("Api Key '{}', calculated hmac '{}'");
// check if signatures match
if (!credentials.getSignature().equals(hmac)) {
throw new BadHMACAuthRequestException("Auth Failed: invalid HMAC signature.");
}
return new RestToken(principal, credentials, restToken.getTimestamp(), apiKeysService.getPermissions(apiKey));
}
#Override
public boolean supports(Class<?> authentication) {
return RestToken.class.equals(authentication);
}
}
I don't know how to configure WebSecurityConfig to authenticate every request with my filter and Authentication Provider. I assume I need to create #Bean to initialize RestSecurityFilter. Also JavaDoc for AbstractAuthenticationProcessingFilter says I need to the authenticationManager property. I would appreciate working solution with custom filter, provider and token.
I'm not familiar with Spring Boot, but I saw your comment on my question How To Inject AuthenticationManager using Java Configuration in a Custom Filter
In a traditional Spring Security XML configuration, you would specify your custom RestSecurityFilter like so
<http use-expressions="true" create-session="stateless" authentication-manager-ref="authenticationManager" entry-point-ref="restAuthenticationEntryPoint">
<custom-filter ref="restSecurityFilter" position="FORM_LOGIN_FILTER" />
</http>
More information http://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/htmlsingle/#ns-custom-filters
I am using spring security and it works fine, but now I want to start the security process manually, do to client changes I need to get in my controller the user name and password (the form wont call "j_spring_security_check" directly)
I thought of 2 options with both I have some problems:
After I get the parameters and do something I will send a post request to j_spring_security_check url. My code:
public void test(loginDTO loginDTO) {
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
HttpHeaders headers = new HttpHeaders();
body.add(
"j_username",
loginDTO.getJ_username());
body.add(
"j_password",
loginDTO.getJ_password());
HttpEntity<?> httpEntity = new HttpEntity<Object>(
body, headers);
headers.add(
"Accept",
MediaType.APPLICATION_JSON_VALUE);
restTemplate.exchange(
"http://localhost:8080/XXX/j_spring_security_check",
HttpMethod.POST,
httpEntity,
HttpServletResponse.class);
}
This doesn't work and I get :500 internal server error why?
second option- I did the following:
public void test2(loginDTO loginDTO, HttpServletRequest request) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(
loginDTO.getJ_username(),
loginDTO.getJ_password());
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = this.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
this.sessionRegistry.registerNewSession(
request.getSession().getId(),
authentication.getPrincipal());
}
The problem is that onAuthenticationSuccess is not called. and it feels wrong, that I'm missing the point of using spring security.
What is the correct why?
I typically do the following:
#Controller
public class AuthenticationController
{
#Autowired
AuthenticationManager authenticationManager;
#Autowired
SecurityContextRepository securityContextRepository;
#RequestMapping(method = Array(RequestMethod.POST), value = Array("/authenticate"))
public String authenticate(#RequestParam String username, #RequestParam String password, HttpServletRequest request, HttpServletResponse response)
{
Authentication result = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
SecurityContextHolder.getContext.setAuthentication(result);
this.securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
return "successView";
}
}
The reasons for using this approach is:
Very simple, just a few lines of code if you ignore exception handling and such.
Leverages existing Spring Security components.
Uses Spring Security components configured in the application configuration and allows them to be changed as and when required. For example, the authentication may be done against an RDBMS, LDAP, web service, Active Directory, etc. without the custom code needing to worry about it.
When you want to use as most as possible from the normal Authentication Process, then you could create a mocked HttpServletRequest and HttpServletResponse (org.springframework.mock.web.MockHttpServletRequest and org.springframework.mock.web.MockHttpServletResponse) containing login and password, and then invoke
UsernamePasswordAuthenticationFilter.attemptAuthentication(
HttpServletRequest request,
HttpServletResponse response)`
afterwards you will also need to invoke SessionAuthenticationStrategy.onAuthentication(..) and successfulAuthentication(..)
This is all a bit tricky, because of private fileds, so this is my solution:
public class ExtendedUsernamePasswordAuthenticationFilter
extends UsernamePasswordAuthenticationFilter {
#Override
public void manualAuthentication(String login,
String password,
HttpServletRequest httpServletRequest)
throws IOException, ServletException {
/** I do not mock the request, I use the existing request and
manipulate them*/
AddableHttpRequest addableHttpRequest =
new AddableHttpRequest(httpServletRequest);
addableHttpRequest.addParameter("j_username", login);
addableHttpRequest.addParameter("j_password", password);
MockHttpServletResponse mockServletResponse =
new MockHttpServletResponse();
Authentication authentication = this.attemptAuthentication(
addableHttpRequest,
mockServletResponse);
this.reflectSessionStrategy().onAuthentication(
authentication,
addableHttpRequest,
mockServletResponse);
this.successfulAuthentication(addableHttpRequest,
mockServletResponse,
authentication);
}
private SessionAuthenticationStrategy reflectSessionStrategy() {
Field sessionStrategyField =
ReflectionUtils.findField(
AbstractAuthenticationProcessingFilter.class,
"sessionStrategy",
SessionAuthenticationStrategy.class);
ReflectionUtils.makeAccessible(sessionStrategyField);
return (SessionAuthenticationStrategy)
ReflectionUtils.getField(sessionStrategyField, this);
}
}
AddableHttpRequest is like a mock that is based on an real request
public class AddableHttpRequest extends HttpServletRequestWrapper {
/** The params. */
private HashMap<String, String> params = new HashMap<String, String>();
public AddableHttpRequest(HttpServletRequest request) {
super(request);
}
#Override
public String getMethod() {
return "POST";
}
#Override
public String getParameter(final String name) {
// if we added one, return that one
if (params.get(name) != null) {
return params.get(name);
}
// otherwise return what's in the original request
return super.getParameter(name);
}
public void addParameter(String name, String value) {
params.put(name, value);
}
}
An other way, would be implementing your own, authentication filter. Thats a class that invoke the AuthenticationManager.authenticate(Authentication authentication). But this class is also responsible for invoking all the stuff around authentication (what AbstractAuthenticationProcessingFilter.doFilter does)`
OK so I combined #Ralph and #manish answers and this is what I did:
(twoFactorAuthenticationFilter is an extension of UsernamePasswordAuthenticationFilter)
public void manualAuthentication(loginDTO loginDTO, HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException {
AddableHttpRequest addableHttpRequest = new AddableHttpRequest(
request);
addableHttpRequest.addParameter(
"j_username",
loginDTO.getJ_username());
addableHttpRequest.addParameter(
"j_password",
loginDTO.getJ_password());
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) twoFactorAuthenticationFilter.attemptAuthentication(
addableHttpRequest,
response);
if (token.isAuthenticated()) {
twoFactorAuthenticationFilter.successfulAuthentication(
addableHttpRequest,
response,
null,
token);
}
}
It works fine
I am testing scribe for facebook authentication. I am not receiving the oauth_verifier when authenticating against facebook - let me know if this is incorrect behavior. For facebook auth, how should I go about creating the verifier in order to create the OAuthRequest.
redirect_uri=http%3A%2F%2Flocalhost%2Foauth%2Ffacebook
Thanks
LoginServlet:
public void doGet(HttpServletRequest req, HttpServletResponse res) {
OAuthService service = new ServiceBuilder().provider(FacebookApi.class).apiKey(FACEBBOK_APP_KEY)
.apiSecret(FACEBOOK_APP_SECRET).callback(FACEBOOK_CALLBACK);
String authenticationUrl = service.getAuthorizationUrl(null);
res.sendRedirect(authenticationUrl);
}
CallbackServlet:
public void doGet(HttpServletRequest req, HttpServletResponse res) {
String code = "";
Enumeration paramEnum = req.getParameterNames();
while (paramEnum.hasMoreElements()) {
String name = (String) paramEnum.nextElement();
if (name.equals("code")) {
code = req.getParameter(name);
}
OAuthService service = new ServiceBuilder().provider(FacebookApi.class).apiKey(FACEBBOK_APP_KEY)
.apiSecret(FACEBOOK_APP_SECRET).callback(FACEBOOK_CALLBACK);
Verifier verifier = new Verifier(code);
//....
}