MyController.java
package com.ivoronline.springboot_security_request_parameters.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@Autowired AuthenticationManager authenticationManager;
@Autowired private UserDetailsService userDetailsService;
@ResponseBody
@RequestMapping("/Authenticate")
public String authenticate(@RequestParam String username, @RequestParam String password) {
//CREATE TOKEN (FROM USERNAME & PASSWORD)
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username,
password);
//AUTHENTICATE
try { authenticationManager.authenticate(authToken); }
catch (BadCredentialsException e) { return "Invalid Credentials"; }
//GET USER OBJECT
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
System.out.println(userDetails);
//SUCCESSFUL AUTHENTICATION
return "Valid Credentials";
}
}
MyLogin.html
<title> MY LOGIN </title>
<style type="text/css">
div { display:flex; flex-direction:column; align-items:center; border: solid 1pt; margin: 10pt 50pt;
background-color: aliceblue }
</style>
<div>
<h2> MY LOGIN </h2>
<form method="POST" action="/Authenticate">
<p> <input type="text" name="username" placeholder="username" /> </p>
<p> <input type="text" name="password" placeholder="password" /> </p>
<p> <input type="submit" name="submit" value="submit" style="width:100%"/> </p>
</form>
</div>