寻找一个简单的 Spring 安全示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4899518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:18:27  来源:igfitidea点击:

Looking for a Simple Spring security example

springspring-mvcspring-security

提问by MushMushon

I am new to spring-security (Java) and I am looking for a good and simpleexample of:

我是 spring-security (Java) 的新手,我正在寻找一个很好的简单示例:

  1. How to use spring security for login and logout

  2. Make sure that the session exists on every page and if not redirect to the login again

  3. How get access to the current User Session

  1. 如何使用spring security进行登录和注销

  2. 确保每个页面上都存在会话,如果没有再次重定向到登录

  3. 如何访问当前用户会话

My project is currently working with spring MVC, and hibernate.
I have built the loginAPI + loginDAO, I need now to combine the security and make some of the pages secured.

我的项目目前正在使用 spring MVC 和休眠。
我已经构建了 loginAPI + loginDAO,我现在需要结合安全性并使一些页面受到保护。

I searched for tutorials, but a lot of them are very complicated.

我搜索了教程,但其中很多都非常复杂。

采纳答案by fatnjazzy

Well. This is I think by far is the best i have seen so far!
http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html

好。这是我认为迄今为止我见过的最好的!
http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html

回答by Abhishek De

You can look for a Single-Sign-On(e.g CAS) implementation in Spring Security. It'll serve your purpose completely.

您可以在 Spring Security 中寻找单点登录(例如 CAS)实现。它将完全符合您的目的。

Check Out :-

查看 :-

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/cas.html

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/cas.html

https://wiki.jasig.org/display/CASC/Using+the+CAS+Client+3.1+with+Spring+Security

https://wiki.jasig.org/display/CASC/Using+the+CAS+Client+3.1+with+Spring+Security

回答by Filipe Cabaco

This is also a great example:

这也是一个很好的例子:

http://www.mkyong.com/spring-security/spring-security-form-login-example/http://krams915.blogspot.pt/2010/12/spring-security-3-mvc-using-simple-user.html

http://www.mkyong.com/spring-security/spring-security-form-login-example/ http://krams915.blogspot.pt/2010/12/spring-security-3-mvc-using-simple-用户.html

Both of them are well documented and are easy to modify for your propose. Krams talks about LDAP using Spring Security.

它们都有很好的文档记录,并且很容易根据您的提议进行修改。Krams 讨论了使用 Spring Security 的 LDAP。

回答by Premraj

Spring Security Tutorial by MKyong

MKyong 的 Spring 安全教程

how to perform database authentication (using both XML and Annotations) in Spring Security.

如何在 Spring Security 中执行数据库认证(同时使用 XML 和 Annotations)。

Technologies used :

使用的技术:

Spring 3.2.8.RELEASE
Spring Security 3.2.3.RELEASE
Spring JDBC 3.2.3.RELEASE
Eclipse 4.2
JDK 1.6
Maven 3
Tomcat 6 or 7 (Servlet 3.x)
MySQL Server 5.6

Spring 3.2.8.RELEASE
Spring Security 3.2.3.RELEASE
Spring JDBC 3.2.3.RELEASE
Eclipse 4.2
JDK 1.6
Maven 3
Tomcat 6 或 7 (Servlet 3.x)
MySQL Server 5.6

SecurityConfig.java

安全配置文件

package com.mkyong.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery(
            "select username,password, enabled from users where username=?")
        .authoritiesByUsernameQuery(
            "select username, role from user_roles where username=?");
    }   

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .and()
          .formLogin().loginPage("/login").failureUrl("/login?error")
          .usernameParameter("username").passwordParameter("password")
        .and()
          .logout().logoutSuccessUrl("/login?logout")
        .and()
          .exceptionHandling().accessDeniedPage("/403")
        .and()
          .csrf();
    }
}

Spring-security.xml

Spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <!-- enable use-expressions -->
    <http auto-config="true" use-expressions="true">

        <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

        <!-- access denied page -->
        <access-denied-handler error-page="/403" />

        <form-login 
            login-page="/login" 
            default-target-url="/welcome" 
            authentication-failure-url="/login?error" 
            username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/login?logout"  />
        <!-- enable csrf protection -->
        <csrf/>
    </http>

    <!-- Select users and user_roles from database -->
    <authentication-manager>
      <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"
          users-by-username-query=
            "select username,password, enabled from users where username=?"
          authorities-by-username-query=
            "select username, role from user_roles where username =?  " />
      </authentication-provider>
    </authentication-manager>

</beans:beans>
  • In above congratulation, the /adminand sub-folders of it are all password protected.
  • login-page=”/login”– The page to display the custom login form
  • authentication-failure-url=”/login?error”– If authentication failed, forward to page /login?error
  • logout-success-url=”/login?logout”– If logout successful, forward to view /logout
  • username-parameter=”username”– The name of the request which contains the “username”. In HTML, this is the name of the input text.
  • <csrf/>– Enable the Cross Site Request Forgery (CSRF) protection
  • 在上面的祝贺中,/admin它的文件夹和子文件夹都受密码保护。
  • login-page=”/login”– 显示自定义登录表单的页面
  • authentication-failure-url=”/login?error”– 如果认证失败,跳转到页面 /login?error
  • logout-success-url=”/login?logout”– 如果注销成功,转发查看 /logout
  • username-parameter=”username”– 包含“用户名”的请求名称。在 HTML 中,这是输入文本的名称。
  • <csrf/>– 启用跨站点请求伪造 (CSRF) 保护

回答by Andrew White

If you haven't already watch this video by the lead developer of Spring Security. It's actually referenced on the Spring Security site but it's easy to miss. Though I do agree, goodSpring Security examples are hard to come by.

如果您还没有观看Spring Security 首席开发人员的这段视频。它实际上在 Spring Security 站点上被引用,但很容易错过。尽管我同意,但很难找到好的Spring Security 示例。