How to get the username (email in my case) in Spring Security [UserDetails/String] - spring

I would like to get the e-mail which is username in my application to set the user which send a message. I decided to use typical method i.e. principal and getUsername():
#PostMapping("/messages/{id}")
#ResponseStatus(HttpStatus.CREATED)
public MessageDTO addOneMessage(#RequestBody MessageRequest messageRequest, #PathVariable ("id") Long id) {
checkIfChannelExists(id);
String content = messageRequest.getContent();
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = ((UserDetails) principal).getUsername();
Employee author = employeeRepository.findByEmail(username).get();
Message message = new Message(content, author, id);
messageRepository.save(message);
return new MessageDTO(message);
}
And MessageRequest.java:
#Data
#NoArgsConstructor
#AllArgsConstructor
public class MessageRequest {
#NonNull
private String content;
}
But, in this way I still get:
"message": "java.lang.String cannot be cast to org.springframework.security.core.userdetails.UserDetails"
What is wrong in my implementation? To be more precise, I use Postman to test POST requests:
{
"content": "something"
}

If you only need to retrieve the username you can get it through Authentication ie.
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
instead of typecasting to your class springcontext provide the almost all details about the user.
If you want the controller to get the user name to test.
please use this code.
//using authentication
#RequestMapping(value = "/name", method = RequestMethod.GET)
#ResponseBody
public String currentUserName(Authentication authentication) {
return authentication.name();
}
//using principal
#RequestMapping(value = "/name", method = RequestMethod.GET)
#ResponseBody
public String currentUserName(Principal principal) {
return principal.getName();
}

Related

Strategy pattern in Spring boot application for payment gateway and methods

I have a controller where I am being passed a gatewayid for different providers. I have a BasePaymentService interface which is implemented by Payu service and Razorpay service for now.
I want to avoid using if condition for and have the strategy added without changing code and have the container inject correct strategy.
How do I add a strategy pattern here?
Would callback method be also a part of strategy here?
How do I account for different payment methods here? (cards, wallets)
BasePaymentService
public interface BasePaymentService {
PaymentDetail makePayment(PaymentDetail detail);
Payment callbackPayment(PaymentCallback detail);
}
Concrete PaymentService
#Service
#Slf4j
public class PayuPaymentService implements BasePaymentService {
#Autowired
PaymentRepository paymentRepository;
public PaymentDetail makePayment(PaymentDetail paymentDetail) {
PaymentUtil paymentUtil = new PaymentUtil();
paymentDetail = paymentUtil.populatePaymentDetail(paymentDetail);
savePaymentDetail(paymentDetail);
return paymentDetail;
}
#Override
public Payment callbackPayment(PaymentCallback paymentResponse) {
log.info("inside callback service >>>>>");
String msg = "Transaction failed.";
Payment payment = paymentRepository.findByTxnId(paymentResponse.getTxnid());
if(payment != null) {
log.info("in condition callback service");
//TODO validate the hash
PaymentStatus paymentStatus = null;
if(paymentResponse.getStatus().equals("failure")){
paymentStatus = PaymentStatus.Failed;
}else if(paymentResponse.getStatus().equals("success")) {
paymentStatus = PaymentStatus.Success;
msg = "Transaction success";
}
payment.setPaymentStatus(paymentStatus);
payment.setMihpayId(paymentResponse.getMihpayid());
payment.setMode(paymentResponse.getMode());
paymentRepository.save(payment);
}
return payment;
}
private void savePaymentDetail(PaymentDetail paymentDetail) {
log.info("in proceedPayment save");
Payment payment = new Payment();
payment.setAmount(Double.parseDouble(paymentDetail.getAmount()));
payment.setEmail(paymentDetail.getEmail());
payment.setName(paymentDetail.getName());
payment.setPaymentDate(new Date());
payment.setPaymentStatus(PaymentStatus.Pending);
payment.setPhone(paymentDetail.getPhone());
payment.setProductInfo(paymentDetail.getProductInfo());
payment.setTxnId(paymentDetail.getTxnId());
paymentRepository.save(payment);
}
}
Controller
#Api(value = "swipe: payment Service", tags = "Example")
#Validated
#RestController
#Slf4j
#RequestMapping(value = CommonConstants.BASE_CONTEXT_PATH)
public class CommonController {
#Autowired
private BasePaymentService paymentService;
#CrossOrigin(origins = "*")
#PostMapping(path = "/payment-details")
public #ResponseBody
PaymentDetail proceedPayment(#RequestBody PaymentDetail paymentDetail){
if(paymentDetail.getGatewayId().equalsIgnoreCase("payu") ){
paymentService.makePayment(paymentDetail);
}
else if(paymentDetail.getGatewayId().equalsIgnoreCase("rp")){
paymentService.makePayment(paymentDetail);
}
return paymentDetail;
}
#CrossOrigin(origins = "*" )
#RequestMapping(path = "/payment-response", method = RequestMethod.POST)
public #ResponseBody
Payment payuCallback(#RequestParam String mihpayid, #RequestParam String status, #RequestParam PaymentMode mode, #RequestParam String txnid, #RequestParam String hash, #RequestParam String amount, #RequestParam String productinfo, #RequestParam String firstname, #RequestParam String lastname, #RequestParam String email, #RequestParam String phone, #RequestParam String error, #RequestParam String bankcode, #RequestParam String PG_TYPE, #RequestParam String bank_ref_num, #RequestParam String unmappedstatus){
log.info("inside callback");
PaymentCallback paymentCallback = new PaymentCallback();
paymentCallback.setMihpayid(mihpayid);
paymentCallback.setTxnid(txnid);
paymentCallback.setMode(mode);
paymentCallback.setHash(hash);
paymentCallback.setStatus(status);
return paymentService.callbackPayment(paymentCallback);
}
}

Receive URL in spring

I try doing confirmation registration from email, on the email I send this code:
String token = UUID.randomUUID().toString(); //for send email
String confirmationUrl = "<a href='" +
"http://localhost:8080/registrationConfirm.html?token="
+ token+"'>Click for end Registration</a>";
helper.setText("message", confirmationUrl.toString());
I receive something like this:
http://localhost:8080/registrationConfirm.html?token=88ab5907-6ab5-40e2-89d5-d6a7e8cea3c2
How I can receive this 88ab5907-6ab5-40e2-89d5-d6a7e8cea3c2 in spring?
I want doing a new controller, he will be check if 88ab5907-6ab5-40e2-89d5-d6a7e8cea3c2 exist in DB, then he activated registration, if no - talk about misstake.
And I do not understand how the conroller will be look, I do so
#RequestMapping(value = "/token", method = RequestMethod.POST)
public #ResponseBody
String getAttr(#PathVariable(value="token") String id,
) {
System.out.println(id);
return id;
}
To complete the comment and hint Ali Dehghani has given (have a look at the answer https://stackoverflow.com/a/17935468/265043):
#RequestMapping(value = "/registrationConfirm", method = RequestMethod.POST)
public #ResponseBody
String getAttr(#RequestParam(value="token") String id) {
System.out.println(id);
return id;
}
Note that I ignored the html suffix in the request mapping annotation. You should read the docs about (default) content negotiation starting at http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-suffix-pattern-match
this another variant
#RequestMapping(value = "/registrationConfirm", method = RequestMethod.POST)
public void getMeThoseParams(HttpServletRequest request){
String goToURL = request.getParameter("token");
System.out.println(goToURL);
}

Login and get information user with token in spring (no OAuth)

I am implementing a project RESTful API, it should login (username / password) and returns a token, I want to use token to retrieve user information.
I follow the instructions:
https://github.com/virgo47/restful-spring-security
But: I do not know how to use it in my function, you can help me with?
#RequestMapping(value = "/login", method = RequestMethod.POST)
public #ResponseBody ResponseObject<Object> login(
#RequestParam(value = "username", required = true) String username,
#RequestParam(value = "password", required = true) String password,
#RequestHeader(value = "token") String token,
HttpSession session) {
//TODO
return new ResponseObject<Object>(1, "Success", data);
}
#RequestMapping(value = "/info", method = RequestMethod.GET)
public #ResponseBody ResponseObject<User> getInfo(#RequestHeader(value = "token", required = true) String token,
HttpSession session) {
//TODO
return null;
}
Why would you want to do that ? Why not just get the logged in user from the SecurityContext as follows
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
System.out.println(" *** MainRestController.test");
// Spring Security dependency is unwanted in controller, typically some
// #Component (UserContext) hides it.
// Not that we don't use Spring Security annotations anyway...
return "SecurityContext: "
+ SecurityContextHolder.getContext().getAuthentication()
.getName();
}
If you insist on doing it, you can do the following.
UserDetails userDetails =
(UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
tokenManager.getUserTokens(userDetails)

Conditional validation in spring mvc

Now I have following controller method signature:
#ResponseBody
#RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
public ResponseEntity setCompanyParams(
#RequestParam("companyName") String companyName,
#RequestParam("email") String email,
HttpSession session, Principal principal) throws Exception {...}
I need to add validation for input parameters.
Now I am going to create object like this:
class MyDto{
#NotEmpty
String companyName;
#Email // should be checked only if principal == null
String email;
}
and I am going to write something like this:
#ResponseBody
#RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
public ResponseEntity setCompanyParams( MyDto myDto, Principal principal) {
if(principal == null){
validateOnlyCompanyName();
}else{
validateAllFields();
}
//add data to model
//return view with validation errors if exists.
}
can you help to achieve my expectations?
That's not the way Spring MVC validations work. The validator will validate all the fields and will put its results in a BindingResult object.
But then, it's up to you to do a special processing when principal is null and in that case look as the validation of field companyName :
#ResponseBody
#RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
public ResponseEntity setCompanyParams(#ModelAttribute MyDto myDto, BindingResult result,
Principal principal) {
if(principal == null){
if (result.hasFieldErrors("companyName")) {
// ... process errors on companyName Fields
}
}else{
if (result.hasErrors()) { // test any error
// ... process any field error
}
}
//add data to model
//return view with validation errors if exists.
}

Mock MVC - Add Request Parameter to test

I am using spring 3.2 mock mvc to test my controller.My code is
#Autowired
private Client client;
#RequestMapping(value = "/user", method = RequestMethod.GET)
public String initUserSearchForm(ModelMap modelMap) {
User user = new User();
modelMap.addAttribute("User", user);
return "user";
}
#RequestMapping(value = "/byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(
#RequestParam("firstName") String firstName,
#RequestParam("lastName") String lastName,
#ModelAttribute("userClientObject") UserClient userClient) {
return client.getUserByName(userClient, firstName, lastName);
}
and I wrote following test:
#Test public void testGetUserByName() throws Exception {
String firstName = "Jack";
String lastName = "s";
this.userClientObject = client.createClient();
mockMvc.perform(get("/byName")
.sessionAttr("userClientObject", this.userClientObject)
.param("firstName", firstName)
.param("lastName", lastName)
).andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$[0].id").exists())
.andExpect(jsonPath("$[0].fn").value("Marge"));
}
what i get is
java.lang.AssertionError: Status expected:<200> but was:<400>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:546)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
Why this happens? Is it right way to pass the #RequestParam
When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error
public void testGetUserByName() throws Exception {
String firstName = "Jack";
String lastName = "s";
this.userClientObject = client.createClient();
mockMvc.perform(get("/byName")
.sessionAttr("userClientObject", this.userClientObject)
.param("firstName", firstName)
.param("lastName", lastName)
).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$[0].id").exists())
.andExpect(jsonPath("$[0].fn").value("Marge"));
}
If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to
#RequestMapping(value = "/byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(
#RequestParam( value="firstName",required = false) String firstName,
#RequestParam(value="lastName",required = false) String lastName,
#ModelAttribute("userClientObject") UserClient userClient)
{
return client.getUserByName(userClient, firstName, lastName);
}
If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :
LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");
mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())
#ModelAttribute is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username and userClient.firstName, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient object.
(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)

Resources