I am securing my web application with OAuth2. I have a custom Authentication Provider which stores the OAuth2Client(OAut2RestTemplate) in the Security Context.
CustomAuthenticationProvide
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
try {
ResourceOwnerPasswordResourceDetails passwordResourceDetails =
(ResourceOwnerPasswordResourceDetails) new OAuth2Client(name, password).getResource();
passwordResourceDetails.setUsername(name);
passwordResourceDetails.setPassword(password);
OAuth2Client client = new OAuth2Client(passwordResourceDetails);
User user = client.getUser();
if (!name.equals(user.getMail())) {
throw new OAuth2AccessDeniedException();
}
return new AuthToken(name, password, new ArrayList<>(), user, client);
} catch (OAuth2AccessDeniedException ex) {
ex.printStackTrace();
return null;
}
}
@Override
public boolean supports(Class<?> aClass) {
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}
AuthToken (Implementation of Authentication object)
public class AuthToken extends UsernamePasswordAuthenticationToken {
private User user;
private OAuth2Client client;
AuthToken(Object principal, String credentials, Collection<? extends GrantedAuthority> authorities, User user, OAuth2Client client) {
super(principal, credentials, authorities);
this.user = user;
this.client = client;
}
AuthToken(String principal, String credentials) {
super(principal, credentials);
}
public User getUser() {
return user;
}
public OAuth2Client getClient() {
return client;
}
}
First of all I want to know if this is secure ? Last time I was logging in. And after a while I saw the orders of the user who logged in after me. My next questin is, if there is a better/more beautiful solution. I was working with the Spring Security OAuth2 Documentation, but I didn't get it work. I had the same Client for all the user.
Example Controller Mapping
@GetMapping(value = "/orders")
public ModelAndView orders(AuthToken token, HttpServletRequest request) {
if (token != null) {
request.getSession().setAttribute("userAcc", token.getUser());
}
user = token.getUser();
List<Statistics> statistics = new ArrayList<>();
try {
List<Order> orders = Arrays.asList(token.getClient().getOrders());
// @TODO Daten Liefern
for (Order order : orders) {
if(!order.getUserid().equals(token.getUser().getId())){
return new ModelAndView("redirect:/logout");
}
Statistics st = new Statistics(order.getProperties(), order.getId());
statistics.add(st);
}
} catch (Exception ex) {
ex.printStackTrace();
}
List<Statistics> statistics_back = new ArrayList<>();
for (int i = statistics.size() - 1; i >= 0; i--) {
statistics_back.add(statistics.get(i));
}
return new ModelAndView("my_orders")
.addObject("statistics", statistics_back);
}