我是Spring MVC框架的初学者,正在构建一个应用程序,在该应用程序中,我拥有的角色和角色在不同的屏幕上具有不同的权限。例如:-在Dashboard用户上具有两个权限(读和写),并且在第二个屏幕页面上用户具有(读取,写入和创建)权限。所以只想知道当我检查权限或以更有效的方式执行此过程的另一种方法时,如何在会话中将此权限与每个屏幕的屏幕类型一起使用。
this my user validation code at login time:-
public String validate(String userName, String password, HttpServletResponse response, HttpServletRequest request,
Model model) {
logger.debug("Starting of the method validate");
System.out.println("validate");
Session session = null;
try {
AppConfig aapConfig = new AppConfig();
List<UsersTable> userList = aapConfig.findAll(UsersTable.class);
System.out.println("############userList length is " +userList.size());
if (!userList.isEmpty()) {
System.out.println("*****************UserList is not emptry");
Map<String, UsersTable> userMap = userList.stream().filter(e -> e.getUsername() != null)
.collect(Collectors.toMap(e -> e.getUsername(), e -> e, (x, y) -> x));
if (userMap.containsKey(userName)) {
UsersTable user = userMap.get(userName);
if (StringUtils.equals(EncryptDecryptPassword.decrypt(user.getUserpassword(), "AirtelSiva"),
password)) {
String userFullName = user.getUserfirstname();
String circleId = user.getUsercircle();
System.out.println("&&&&&&&&&& Circle ID is "+circleId);
HttpSession httpSession =request.getSession();
String id = httpSession.getId();
System.out.println(id);
httpSession.setAttribute("userFullName", userFullName);
httpSession.setAttribute("userName", userName);
httpSession.setAttribute("circleId", circleId);
// saving the userName with the unique session Id
UserSession userSession = new UserSession();
userSession.setUserName(userName);
userSession.setSessionId(id);
return"";
}
使用spring-security
,您可以毫不费力地提供此授权。将所需的依赖项添加到POM
并配置身份验证。请记住,添加spring-security
依赖项时,其版本应与您使用的Spring版本兼容。
您可以简单地提供身份验证和授权,例如
@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure( AuthenticationManagerBuilder auth ) throws Exception
{
// Using in-memory authentication
User.UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser( users.username( "john" ).password( "john1234" ).roles( "READ", "WRITE" ) )
.withUser( users.username( "doe" ).password( "doe1234" ).roles( "READ", "WRITE", "CREATE" ) );
}
/**
* This allows adding custom login-form and add HTTP URL security
*
* @param http
* @throws Exception
*/
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http.authorizeRequests()
.antMatchers( "/" ).permitAll()
.antMatchers( "/dashboard" ).hasAnyRole( "READ","WRITE" )
.antMatchers( "/anotherPage" ).hasAnyRole( "READ","WRITE","CREATE" )
// Other necessary validations like CSRF or cookie policy
}
请在春季官方文档here中找到该教程。