Setting up the controller

This is the final setup in our CAS client project setup. We will have an unsecured page containing a link to a secured page. When the secured page is accessed, CAS SSO kicks in and the user is navigated to the CAS authentication page. Once you log in using the credentials (casuser/password), the user is taken to the secured page, where we display the authenticated username.

We will create an ndexController that has the root folder routing (/). This navigates the user to the index.html page.

Create IndexController.java in a new package (preferably in the controllers package):

@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
}

Create the index.html file in the src/resources/templates folder with the following content:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Spring Security CAS Sample - Unsecured page</title>
</head>
<body>
<h1>Spring Security CAS Sample - Unsecured page</h1>
<br>
<a href="/secured">Go to Secured Page</a>
</body>
</html>

Now create a new controller named CasController.java within the same controllers package. We will be mapping all secured pages as well as setting up various request mappings in this controller. In the controller class, copy the following code snippet:

@Controller
@RequestMapping(value = "/secured")
public class CasController {

@GetMapping
public String secured(ModelMap modelMap) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if( auth != null && auth.getPrincipal() != null
&& auth.getPrincipal() instanceof UserDetails) {
modelMap.put("authusername", ((UserDetails) auth.getPrincipal()).getUsername());
}
return "secured";
}
}

Create a new HTML file named secured.html with the following content. This is our secured page and will just display the authenticated username:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Spring Security CAS Sample - Secured page</title>
</head>
<body>
<h1>Spring Security CAS Sample - Secured page</h1>
<br>
<h3 th:text="${authusername} ? 'Hello authenticated user, ' + ${authusername} + '!' : 'Hello non-logged in user!'">Hello non-logged in user!</h3>
</body>
</html>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.60.158