英文:
how to apply screen by screen permisssion in Spring mvc?
问题
我是Spring MVC框架的初学者,正在构建一个应用程序,在这个应用程序中,我有一个角色,角色在不同的屏幕上具有不同的权限。例如:在仪表板上,用户有两个权限(读取和写入),而在第二个屏幕页面上,用户有(读取、写入和创建)权限。所以我想知道如何将这些权限与会话一起存储,以便在每个屏幕上检查权限时获取这些权限或者是否有其他更有效的方法来完成这个过程。
这是我在登录时的用户验证代码:
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 empty");
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 "";
}
}
}
}
请注意,这只是代码的一部分,涉及用户验证和会话管理。要实现屏幕级别的权限管理,您需要在系统中定义角色、权限和屏幕,并在每个屏幕上根据用户的角色和权限来控制访问。如果需要更多关于权限管理的帮助,请提出具体的问题。
英文:
I am a beginner in spring MVC framework and I am building an application in which I have a role and role have different permissions on different screen .like:- on Dashboard user have two permissions (Read and write) and in second screen page user have (Read , Write and Create) permission.
so just want to know how could I put this permission with the session to get these in with the screen type at each screen when I am checking the permission or another method to do this process in a more effective way.
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"";
}
答案1
得分: 2
使用spring-security
,您可以以最小的努力提供此授权。将所需的依赖项添加到您的POM
并配置身份验证。请注意,在添加spring-security
依赖项时,其版本应与您使用的spring版本兼容。
您可以简单地提供身份验证和授权,如下所示:
@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure( AuthenticationManagerBuilder auth ) throws Exception
{
// 使用内存中的身份验证
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" )
.anyRequest()
.authenticated()
.and()
.formLogin() // Add form login
.loginPage( "/showMyLoginPage" ) // Pointing to custom login form. This line is optional as spring by default provides a login page
.loginProcessingUrl( "/authenticateTheUser" ) // No coding needed. Just provide some endpoint. You need not implement this endpoint. Spring will take care of it.
.permitAll()
// Other necessary validations like CSRF or cookie policy
}
}
请在spring官方文档的这里找到教程。
在使用Spring-security
进行授权后,您可以要求模板引擎[如果支持]根据已登录用户的角色显示或隐藏页面的特定部分。
作为示例,以下是如何在JSP中基于用户角色隐藏链接的方法,通过添加类似<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
的安全支持。
在这里,只有拥有ADMIN
角色的用户才能看到此链接。
<security:authorize access="hasRole('ADMIN')">
<hr>
<p><a href="${pageContext.request.contextPath}/admin">Link to admin page</a> ( Only admin can see this )</p>
<hr>
</security:authorize>
这个链接包含了开始使用spring-security
所需的所有详细信息。
英文:
With spring-security
, you can provide this authorization with minimal effort. Add the required dependencies to your POM
and configure the authentication. Keep in mind, when adding the spring-security
dependency, its version should be compatible with the spring version you are using.
You can simply provide authentication and authorization like
@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" )
.anyRequest()
.authenticated()
.and()
.formLogin() // Add form login
.loginPage( "/showMyLoginPage" ) // Pointing to custom login form. This line is optional as spring by default provides a login page
.loginProcessingUrl( "/authenticateTheUser" ) // No coding needed. Just provide some endpoint. You need not implement this endpoint. Spring will take care of it.
.permitAll()
// Other necessary validations like CSRF or cookie policy
}
Please find the tutorial on the spring official doc here.
And once you do the authorization with Spring-security
. You can ask your template engine [if it support]. to show or hide certain sections of the page depending on the roles of the logged user.
As an example, here's how you could hide a link based on the user role in JSP by adding the security support like <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
Here, only users having role ADMIN
can see this link.
<security:authorize access="hasRole('ADMIN')">
<hr>
<p><a href="${pageContext.request.contextPath}/admin">Link to admin page</a> ( Only admin can see this )</p>
<hr>
</security:authorize>
This link contain all the necessary detail to get started on spring-security
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论