How to create a token for a role in dropwizard? - java

I am trying to create a login token for a user. Let's call that user "manager". There are already existing tokens for different roles. The manager role is a role such that the manager can also be an agent. Thus, a manager should be able to login on two different platforms - Mobile and Web and the manager should not be logged out from either of the platforms.
Here is what the profile service looks like.
public class ProfileService {
private String baseUrl;
private ObjectMapper objectMapper;
public ProfileService(String baseUrl) {
this.baseUrl = baseUrl;
objectMapper = new ObjectMapper();
}
public ProfileDTO fetchUserProfile(String profileId){
Client client = ClientBuilder.newClient();
log.info("This is the base url {}", baseUrl);
Map response = client.target(baseUrl + "/api/v1/users/" + profileId).request().get(Map.class);
Object data = response.get("data");
Map dataMap = this.objectMapper.convertValue(data, Map.class);
Map roleGroup = this.objectMapper.convertValue(dataMap.get("roleGroup"), Map.class);
List roleObjs = this.objectMapper.convertValue(dataMap.get("roles"), List.class);
String userType = dataMap.get("userType").toString();
String roleGroupName = (Objects.isNull(roleGroup)) ? userType : roleGroup.get("name").toString();
List<String> roles = new ArrayList<>();
if (Objects.nonNull(roleObjs)) {
for (Object entry : roleObjs) {
Map role = this.objectMapper.convertValue(entry, Map.class);
roles.add(role.get("name").toString().toUpperCase(Locale.ROOT));
}
}
return new ProfileDTO(dataMap.get("id").toString(), dataMap.get("email").toString(),
dataMap.get("firstName").toString(), roleGroupName, userType,
roles, (Boolean) dataMap.get("enabled"), (Boolean) dataMap.get("verified"));
}
}
Here is the existing service that is not giving me the desired results.
private void verify(ProfileDTO profile, Types.Platform platform) throws AuthenticationException {
if (!profile.isEnabled() || profile.getUserType() == null) {
throw new AuthenticationException("Unauthorized!");
}
switch (platform) {
case WEB:
if(!profile.getUserType().equalsIgnoreCase(Constants.STAFF_ROLE)){
throw new AuthenticationException("Unauthorized web platform user");
}
return;
case MOBILE:
if (!profile.getUserType().equalsIgnoreCase(Constants.AGENT_ROLE)){
throw new AuthenticationException("Unauthorized mobile platform user");
}
return;
case AGGREGATOR:
if(!profile.getRoles().add("AGGREGATOR_ROLE")){
throw new AuthenticationException("Unauthorized aggregator");
}
default:
throw new AuthenticationException("Unauthorized! Unknown platform");
}
}
private String generateToken(ClPrincipal principal) throws JoseException {
final JwtClaims claims = new JwtClaims();
claims.setSubject(principal.getProfileId());
claims.setStringClaim(Constants.USERNAME, principal.getUsername());
claims.setStringClaim(Constants.FIRST_NAME, principal.getFirstname());
claims.setStringClaim(Constants.LAST_NAME, principal.getLastname());
claims.setStringClaim(Constants.ROLE_GROUP, principal.getRoleGroup());
claims.setStringListClaim(Constants.ROLES, principal.getRoles());
claims.setExpirationTimeMinutesInTheFuture(oAuthConfig.getTokenTTL() / 60);
claims.setJwtId(UUID.randomUUID().toString())
What do I do to get the desired result I stated earlier. I keep getting the default message for the switch case ("Unauthorized! Unknown platform")

Related

if password is incorrect then login attempts store into database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am a beginner in spring security.
I have implement UserDetailsService interface of method public UserDetails loadUserByUsername(String email)
My problem is below.......
username and password both are entered wrong then it can work properly. but when I enter the correct username and incorrect password then I want to add an attempt in the database otherwise not. if the username and password are correct then I don't want to update attempt into the database.
private static final int MAX_ATTEMPTS = 3;
int MIN_ATTEMPTS = 0;
#Override
public UserDetails loadUserByUsername(String email) {
Members members = membersDao.findByEmail(email);
Set<GrantedAuthority> authorities = new HashSet<>();
if (members == null) {
throw new RuntimeException("Invalid username and password");
} else {
if (members == null) {
} else {
MIN_ATTEMPTS = members.getAttempts();
MIN_ATTEMPTS ++;
members.setAttempts(MIN_ATTEMPTS);
membersDao.save(members);
throw new RuntimeException("Login Attepmts "+MIN_ATTEMPTS);
}
if (members.getAttempts() <= MAX_ATTEMPTS) {
Role role = members.getRoles();
authorities.add(new SimpleGrantedAuthority(role.getRole()));
return new User(members.getEmail(), members.getPassword(),authorities);
} else {
throw new RuntimeException("blocked");
}
}
}
Ive tryed to change your Code a bit
private static final int MAX_ATTEMPTS = 3;
#Override
public UserDetails loadUserAndCheckLogin(String email, String enteredPassword) {
Members members = membersDao.findByEmail(email);
if (members == null) {
//Create Error Message for User
return null;
}
if (members.getAttempts() > MAX_ATTEMPTS) {
//Create Error Message for User
return null;
}
if (members.getPassword().equals(enteredPassword)) {
Set<GrantedAuthority> authorities = new HashSet<>();
Role role = members.getRoles();
authorities.add(new SimpleGrantedAuthority(role.getRole()));
members.setAttempts(0);
membersDao.save(members);
return new User(members.getEmail(), members.getPassword(), authorities);
} else {
int attempts = members.getAttempts();
members.setAttempts(++attempts);
membersDao.save(members);
//Create Error Message for User
return null;
}
}
Btw. im not sure if you realy want to create a new "SimpleGrantedAuthority" and "User" or if you want to load existing ones from your Database.
And you should use a hash for your Passwords.
Login controller
#PostMapping("/login")
public ResponseEntity<?> login(#RequestBody LoginMembers loginMembers) throws AuthenticationException, IOException, ServletException {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginMembers.getEmail(),
loginMembers.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
final String token = jwtTokenUtil.generateToken(authentication);
logger.info("You are log in successfully with token");
return ResponseEntity.ok(new AuthTokenRequest(token));
}
I have customize your code and add into calling Method as per you suggest #Pitzas
thanks for suggest me............
private static final int MAX_ATTEMPTS = 3;
#PostMapping("/login")
public ResponseEntity<?> login(#RequestBody LoginMembers loginMembers) throws AuthenticationException, IOException, ServletException {
Members members = membersDao.findByEmail(loginMembers.getEmail());
PasswordEncoder passencoder = new BCryptPasswordEncoder();
if (members == null) {
//Create Error Message for User
throw new RuntimeException("Invalid Username and Password");
}
if (members.getAttempts() >= MAX_ATTEMPTS) {
//Create Error Message for User
throw new RuntimeException("Login Attempt exceeds "+MAX_ATTEMPTS);
}
if (passencoder.matches(loginMembers.getPassword(), members.getPassword())) {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginMembers.getEmail(),
loginMembers.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
final String token = jwtTokenUtil.generateToken(authentication);
logger.info("You are log in successfully with token");
return ResponseEntity.ok(new AuthTokenRequest(token));
} else {
int attempts = members.getAttempts();
members.setAttempts(++attempts);
membersDao.save(members);
//Create Error Message for User
throw new RuntimeException("Login attempts "+attempts);
}
}

steam OpenID authentication without a callback-URL

I am trying how to add a steam logging to my java application .I have try out few OpenID libraries in http://openid.net/developers/libraries, And this is for JOpenID ,
Eg - >
OpenIdManager manager = new OpenIdManager();
manager.setTimeOut(10000);
Endpoint endpoint = manager.lookupEndpoint("http://steamcommunity.com/openid");
System.out.println(endpoint);
Association association = manager.lookupAssociation(endpoint);
System.out.println(association);
String url = manager.getAuthenticationUrl(endpoint, association);
System.out.println("Copy the authentication URL in browser:\n" + url);
System.out.println("After successfully sign on in browser, enter the URL of address bar in browser:");
String ret = url;
HttpServletRequest request = createRequest(ret);
Authentication authentication = manager.getAuthentication(request, association.getRawMacKey(), endpoint.getAlias());
System.out.println(authentication);
Because i am not trying this for web app and I Dont have a callback-URL to use , i have use "easymock"
public HttpServletRequest createRequest(String url) throws UnsupportedEncodingException {
int pos = url.indexOf('?');
if (pos==(-1))
throw new IllegalArgumentException("Bad url.");
String query = url.substring(pos + 1);
String[] params = query.split("[\\&]+");
final Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
pos = param.indexOf('=');
if (pos==(-1))
throw new IllegalArgumentException("Bad url.");
String key = param.substring(0, pos);
String value = param.substring(pos + 1);
map.put(key, URLDecoder.decode(value, "UTF-8"));
}
return (HttpServletRequest) Proxy.newProxyInstance(
Main.class.getClassLoader(),
new Class[] { HttpServletRequest.class },
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("getParameter"))
return map.get((String)args[0]);
throw new UnsupportedOperationException(method.getName());
}
}
);
}
But I am getting a error saying ,
java.lang.IllegalArgumentException: interface javax.servlet.http.HttpServletRequest is not visible from class loader
at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:487)
at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:722)
and i have ALSO try as the code like in
https://gist.github.com/FernFerret/7692878 too (for Openid4java and spark) but got error when creating Route like in link saying there is no 'Route(String)'
get(new Route("/") {
So how can i Make OpenID authentication with out a Redirect URL ?
Can any one can guide me for a java OpenID Authentication for Steam using "any" OpenID code ?
I just need That returned value( like-> http//steamcommunity.com/openid/id/76561197960435530") informed in
http://steamcommunity.com/dev/
Which is the only value that returns .
Many Thanks For Any inputs !!

ExactTarget SOAP Client Using CXF

I am looking to build a stand-alone ExactTarget SOAP client using CXF.
I was able to create a client using Glassfish Metro, but due to future support considerations we would like to use CXF. I found an old example and associated project, but it is too old to be useful.
Currently I am trying to understand how can I set a handler on the stub/port object and to pass dynamic username and password to it. By dynamic I mean: the app gets username and password from the user at the time of running. Here is the code that I currently have for the Metro implementation:
PartnerAPI service = new PartnerAPI();
Soap stub = service.getSoap();
Map<String, Object> outProperties = new HashMap<String, Object>();
Map ctx = ((BindingProvider) stub).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, user);
requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
List<Handler> chain = new ArrayList<Handler>();
chain.add(new SecurityHandler());
((BindingProvider) stub).getBinding().setHandlerChain(chain);
I am trying to reuse the first 4-6 lines for the CXF implementation, but I cannot use the handlers I have since they depend on com.sun.xml.wss.XWSSProcessor.
Here is code that does everything:
private static Soap createApiStub() {
PartnerAPI service = new PartnerAPI();
Soap stub = service.getSoap();
Client client = org.apache.cxf.frontend.ClientProxy.getClient(stub);
Map<String, Object> outProps = new HashMap<String, Object>();
outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
outProps.put(WSHandlerConstants.USER, username);
outProps.put(WSHandlerConstants.PASSWORD_TYPE,WSConstants.PW_TEXT);
// Automatically adds a Base64 encoded message nonce and a created timestamp
outProps.put(WSHandlerConstants.ADD_UT_ELEMENTS,WSConstants.NONCE_LN + " " + WSConstants.CREATED_LN);
outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new ClientPasswordCallback(username, password));
WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);
client.getOutInterceptors().add(wssOut);
//Enable GZip compression
Map<String, java.util.List<String>> httpHeaders = new HashMap<String, java.util.List<String>>();
httpHeaders.put("Content-Encoding",Collections.singletonList("gzip"));
httpHeaders.put("Accept-Encoding",Collections.singletonList("gzip"));
Map<String, Object> reqContext = client.getRequestContext();
reqContext.put(MessageContext.HTTP_REQUEST_HEADERS,httpHeaders);
return stub;
}
And here is handler implementation:
public class ClientPasswordCallback implements CallbackHandler {
private String username;
private String password;
public ClientPasswordCallback(String username, String password) {
this.username = username;
this.password = password;
}
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
for (Callback callback: callbacks){
if (callback instanceof WSPasswordCallback){
WSPasswordCallback pc = (WSPasswordCallback) callback;
if (username.equals(pc.getIdentifier())) {
pc.setPassword(password);
}
} else if (callback instanceof NameCallback){
throw new UnsupportedCallbackException(callback);
} else {
throw new UnsupportedCallbackException(callback);
}
}
}
}
This answer helped me to pass the password dynamiclly.

Web app and request authentication

I currently have a working web app, but I need to provide means for friend website to consume my data.
There is currently JSON response in place which retrieves some data from my website to caller. It's without authentication currently and I'd like to implement some kind of per request authentication.
My web app has users which are logged in and there is a authentication in place for that. But
I have 3 requests in total for which callers can get data off of my website, what would be the simplest way to add some kind of authentication just for those 3 requests?
I'm using play framework + java
Imo the best options for this would be in the order of simplicity:
Basic authentication (since it's possible to choose either to auth once and then do session-base user recognition or authorize on every request)
2-way SSL
Combination of both
What toolkit do you use for authentication part?
I personally stuck with play-authenticate. So I might be able to answer you question in regard to this toolkit, please apply it to your particular toolkit as needed.
I will provide Basic authentication example as the easiest one. The benefit is: you could start with it and add on top it later (e.g. add Client certificate authentication via Apache later on).
So, my controller code snippet
#Restrict(value = #Group({"ROLE_WEB_SERVICE1"}), handler = BasicAuthHandler.class)
public static Result ws1() {
return TODO;
}
And the authentification handler itself
public class BasicAuthHandler extends AbstractDeadboltHandler {
public static final String HEADER_PREFIX = "Basic ";
private static final String AUTHORIZATION = "authorization";
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
#Override
public Result beforeAuthCheck(final Http.Context context) {
return basicAuthenticate(context);
}
private Result basicAuthenticate(Http.Context context) {
if (PlayAuthenticate.isLoggedIn(context.session())) {
// user is logged in
return null;
}
final String authHeader = context.request().getHeader(AUTHORIZATION);
if (authHeader == null || !authHeader.toLowerCase().startsWith(HEADER_PREFIX.toLowerCase())) {
return onAuthFailure(context, "Basic authentication header is missing");
}
final String auth = authHeader.substring(HEADER_PREFIX.length());
final byte[] decodedAuth;
final String[] credentials;
try {
decodedAuth = Base64.base64ToByteArray(auth);
credentials = new String(decodedAuth, "UTF-8").split(":");
} catch (final IOException e) {
Logger.error("basicAuthenticate", e);
return Results.internalServerError();
}
if (credentials.length != 2) {
return onAuthFailure(context, "Could not authenticate with absent password");
}
final String username = credentials[0];
final String password = credentials[1];
final AuthUser authUser = new AuthUser(password, username);
final Enum result = AuthProvider.getProvider().loginUser(authUser);
if ("USER_LOGGED_IN".equals(result.name())) {
PlayAuthenticate.storeUser(context.session(), authUser);
return null;
}
return onAuthFailure(context, "Authenticate failure");
}
#Override
public Subject getSubject(final Http.Context context) {
// your implementation
}
#Override
public Result onAuthFailure(final Http.Context context,
final String content) {
// your error hangling logic
return super.onAuthFailure(context, content);
}
}
Hopefully it fills in some blanks

GWT Facebook Integration

I am trying to write a server side Facebook Notification service in my GWT app. The idea is that I will run this as a timertask or cron job sort of.
With the code below, I get a login URL, I want to be able to Login programmatically as this is intended to be automated (Headless sort of way). I was gonna try do a submit with HTMLunit but I thought the FB API should cater for this.
Please advice.
public class NotificationServiceImpl extends RemoteServiceServlet implements NotificationService {
/**serialVersionUID*/
private static final long serialVersionUID = 6893572879522128833L;
private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";
long facebookUserID;
public String sendMessage(Notification notification) throws IOException {
String api_key = notification.getApi_key();
String secret = notification.getSecret_key();
try {
// MDC.put(ipAddress, req.getRemoteAddr());
HttpServletRequest request = getThreadLocalRequest();
HttpServletResponse response = getThreadLocalResponse();
HttpSession session = getThreadLocalRequest().getSession(true);
// session.setAttribute("api_key", api_key);
IFacebookRestClient<Document> userClient = getUserClient(session);
if(userClient == null) {
System.out.println("User session doesn't have a Facebook API client setup yet. Creating one and storing it in the user's session.");
userClient = new FacebookXmlRestClient(api_key, secret);
session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
}
System.out.println("Creating a FacebookWebappHelper, which copies fb_ request param data into the userClient");
FacebookWebappHelper<Document> facebook = new FacebookWebappHelper<Document>(request, response, api_key, secret, userClient);
String nextPage = request.getRequestURI();
nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1); //cut out the first /, the context path and the 2nd /
System.out.println(nextPage);
boolean redirectOccurred = facebook.requireLogin(nextPage);
if(redirectOccurred) {
return null;
}
redirectOccurred = facebook.requireFrame(nextPage);
if(redirectOccurred) {
return null;
}
try {
facebookUserID = userClient.users_getLoggedInUser();
if (userClient.users_hasAppPermission(Permission.STATUS_UPDATE)) {
userClient.users_setStatus("Im testing Facebook With Java! This status is written using my Java code! Can you see it? Cool :D", false);
}
} catch(FacebookException ex) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while fetching user's facebook ID");
System.out.println("Error while getting cached (supplied by request params) value " +
"of the user's facebook ID or while fetching it from the Facebook service " +
"if the cached value was not present for some reason. Cached value = {}" + userClient.getCacheUserId());
return null;
}
// MDC.put(facebookUserId, String.valueOf(facebookUserID));
// chain.doFilter(request, response);
} finally {
// MDC.remove(ipAddress);
// MDC.remove(facebookUserId);
}
return String.valueOf(facebookUserID);
}
public static FacebookXmlRestClient getUserClient(HttpSession session) {
return (FacebookXmlRestClient)session.getAttribute(FACEBOOK_USER_CLIENT);
}
}
Error message:
[ERROR] com.google.gwt.user.client.rpc.InvocationException: <script type="text/javascript">
[ERROR] top.location.href = "http://www.facebook.com/login.php?v=1.0&api_key=MY_KEY&next=notification";
[ERROR] </script>

Categories