揭秘Spring Security自定义登录全流程:5步实现高安全性登录页面

Spring Security-自定义登录页面和认证过程其他常用配置 虽然Spring Security给我们提供了登录页面,但是对于实际项目中,大多喜欢使用自己的登录页面。所以Spring Security中不仅仅提供了登录页面,还支持用户自定义登录页面。实现过程也比较简单,只需要修改配置类即可。1.编写登录页面别写登录页面,登录页面中的action不编写对应控制器也可以。 2.修改配置类​ 修改配置类中主要是设置哪个页面是登录页面。配置类需要继承WebSecurityConfigurerAdapter,并重写configure方法。​ successForwardUr 阅读详情

第一章:揭秘Spring Security自定义登录的核心机制

Spring Security 作为 Java 生态中最主流的安全框架,其默认的表单登录机制虽然开箱即用,但在实际项目中往往需要支持自定义登录逻辑,例如基于手机号、验证码、第三方令牌等方式认证。理解其底层机制是实现灵活扩展的前提。

认证流程的核心组件

在 Spring Security 中,自定义登录的关键在于介入认证流程的执行链。核心组件包括:
  • AuthenticationManager:负责协调认证流程,委托给合适的 Provider 处理
  • AuthenticationProvider:具体实现认证逻辑,如校验用户名密码
  • UsernamePasswordAuthenticationToken:封装用户凭证的载体
  • SecurityContext:存储认证后的用户信息

自定义登录的实现步骤

要实现非标准登录方式(如短信验证码),需注册自定义过滤器并跳过默认认证流程:

// 自定义过滤器示例
public class CustomAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        if (!"POST".equals(request.getMethod()) || !"/login/custom".equals(request.getServletPath())) {
            chain.doFilter(request, response);
            return;
        }

        String phone = request.getParameter("phone");
        String code = request.getParameter("code");

        // 构造自定义令牌
        Authentication token = new UsernamePasswordAuthenticationToken(phone, code);
        Authentication result = authenticationManager.authenticate(token);

        // 将认证结果存入上下文
        SecurityContextHolder.getContext().setAuthentication(result);
        response.getWriter().write("{\"status\":\"success\"}");
    }
}
该过滤器拦截特定请求,提取参数并提交给 AuthenticationManager 进行认证。

配置优先级与过滤器注册

为确保自定义过滤器生效,必须在安全配置中正确设置顺序:
过滤器名称默认顺序是否可替换
CustomAuthenticationFilter1是
UsernamePasswordAuthenticationFilter2是
BasicAuthenticationFilter3否

第二章:搭建安全的自定义登录环境

2.1 理解Spring Security默认认证流程

Spring Security在未显式配置时会启用默认的安全机制,其核心是基于过滤器链的认证流程。应用启动后,自动注册一系列安全过滤器,其中关键的是`UsernamePasswordAuthenticationFilter`,负责处理表单登录请求。
默认认证流程步骤
  1. 用户访问受保护资源,触发安全拦截
  2. 系统重定向至默认登录页面(/login)
  3. 提交用户名密码,由过滤器捕获并构建认证令牌
  4. 交由`AuthenticationManager`验证凭据
  5. 成功后分配权限并建立会话
典型过滤器链结构
过滤器名称职责
SecurityContextPersistenceFilter管理安全上下文生命周期
UsernamePasswordAuthenticationFilter处理登录请求
FilterSecurityInterceptor执行访问控制决策

// 默认配置等效代码
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .anyRequest().authenticated() // 所有请求需认证
        )
        .formLogin(Customizer.withDefaults()); // 启用默认登录页
    return http.build();
}
上述配置启用标准表单登录流程,Spring Security自动生成/login页面,并使用内存中用户存储进行认证校验。

2.2 配置WebSecurityConfigurerAdapter基础设置

在Spring Security中,`WebSecurityConfigurerAdapter`是配置安全策略的核心类。通过继承该类并重写其方法,可定义认证机制、授权规则和安全过滤链。
启用Web安全配置
使用`@EnableWebSecurity`注解激活安全配置,并继承`WebSecurityConfigurerAdapter`:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll() // 允许访问公开路径
                .anyRequest().authenticated() // 其他请求需认证
            .and()
            .formLogin(); // 启用表单登录
    }
}
上述代码中,`HttpSecurity`用于构建请求级别的安全控制。`authorizeRequests()`启动URL权限管理,`antMatchers`指定特定路径的访问策略,`formLogin()`启用默认登录页面。
常用配置选项
  • permitAll():无需身份验证即可访问
  • authenticated():必须经过认证
  • hasRole("ADMIN"):要求具备特定角色
  • httpBasic():启用HTTP Basic认证

2.3 引入自定义登录页面与静态资源处理

在Spring Security应用中,默认的登录界面虽然便于快速开发,但无法满足实际项目对UI/UX的需求。因此,引入自定义登录页面成为必要步骤。
配置自定义登录入口
通过重写`configure(HttpSecurity http)`方法,指定登录页面路径:
http
    .formLogin()
        .loginPage("/login") // 指向自定义登录页
        .permitAll()
    .and()
    .authorizeRequests()
        .requestMatchers("/css/**", "/js/**").permitAll() // 放行静态资源
        .anyRequest().authenticated();
上述代码中,loginPage("/login")指示认证失败时跳转至自定义登录页;而permitAll()确保未认证用户可访问登录页及其依赖资源。
静态资源放行策略
为避免CSS、JS等文件被安全过滤器拦截,需显式放行:
  • /css/**:允许加载样式文件
  • /js/**:允许加载JavaScript脚本
  • /images/**:支持图片资源访问
将这些路径置于authorizeRequests()之前,保障前端渲染完整性。

2.4 启用表单登录并禁用CSRF保护(开发阶段)

在开发阶段,为简化调试流程,可临时启用基于表单的登录认证并关闭CSRF防护机制。
配置Spring Security
通过重写`configure(HttpSecurity)`方法,启用表单登录并禁用CSRF:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()  // 禁用CSRF(仅限开发环境)
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin();  // 启用默认登录表单
}
上述代码中,`.csrf().disable()`关闭了跨站请求伪造防护,提升开发调试效率;`.formLogin()`启用内置登录页面,无需手动实现认证接口。
安全注意事项
  • 禁用CSRF仅适用于本地开发,生产环境必须启用
  • 建议通过配置文件区分环境,动态控制安全策略

2.5 实践:构建HTML登录界面并与Spring MVC集成

创建HTML登录表单
使用标准HTML5语法构建登录页面,确保表单字段与后端模型对齐:
<form action="/login" method="post">
  <input type="text" name="username" placeholder="用户名" required>
  <input type="password" name="password" placeholder="密码" required>
  <button type="submit">登录</button>
</form>
该表单通过POST提交至/login路径,字段名与Spring控制器参数一致,required属性增强前端校验。
Spring MVC控制器映射
在控制器中定义处理方法,接收表单数据并返回视图:
@PostMapping("/login")
public String handleLogin(@RequestParam String username, @RequestParam String password) {
    // 简化验证逻辑
    if ("admin".equals(username) && "123456".equals(password)) {
        return "dashboard";
    }
    return "login";
}
@RequestParam注解绑定请求参数,方法根据验证结果决定跳转页面,实现基础认证流程。

第三章:实现用户认证与权限控制

3.1 理论:UserDetailsService与PasswordEncoder机制解析

用户详情服务机制

UserDetailsService 是 Spring Security 中用于加载用户特定数据的核心接口。其实现需重写 loadUserByUsername 方法,返回 UserDetails 对象,包含用户名、密码、权限等信息。

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("User not found");
    }
    return new org.springframework.security.core.userdetails.User(
        user.getUsername(),
        user.getPassword(),
        getAuthorities()
    );
}

上述代码从数据库查询用户,并封装为安全上下文所需的 UserDetails 实例。异常处理确保认证失败时抛出标准异常。

密码加密策略

PasswordEncoder 提供密码的加密与验证,防止明文存储。常用实现如 BCryptPasswordEncoder,采用强哈希算法。

  • 加密:注册时对原始密码进行哈希处理
  • 比对:登录时自动比对输入密码与存储哈希值
  • 无须解密:基于单向哈希,保障安全性

3.2 编写自定义UserDetailsService加载用户信息

在Spring Security中,UserDetailsService接口负责根据用户名加载用户信息。默认实现可能无法满足复杂业务需求,因此常需编写自定义实现。
实现自定义服务
创建类实现UserDetailsService接口,重写loadUserByUsername方法:

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
        return org.springframework.security.core.userdetails.User
            .withUsername(user.getUsername())
            .password(user.getPassword())
            .authorities(new SimpleGrantedAuthority(user.getRole()))
            .build();
    }
}
上述代码从数据库查询用户,封装为UserDetails对象。若用户未找到,则抛出异常,触发认证失败流程。
核心优势
  • 灵活集成任意数据源,如数据库、LDAP或远程API
  • 支持细粒度权限控制与用户状态管理

3.3 实践:配置BCrypt密码编码器保障密码安全

在Spring Security中,使用BCrypt密码编码器是保护用户密码的行业标准做法。BCrypt通过加盐和自适应哈希机制,有效抵御彩虹表和暴力破解攻击。
配置BCryptPasswordEncoder
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12); // 强制使用强度等级12
}
上述代码创建了一个BCryptPasswordEncoder实例,参数12表示哈希的强度(轮数为2^12),数值越高安全性越强,但计算耗时也增加。推荐在生产环境中使用10~14之间的值以平衡安全与性能。
密码加密与验证流程
  • 用户注册时,明文密码经BCrypt加密生成含盐哈希值并存储
  • 用户登录时,输入密码再次哈希并与数据库值比对
  • Spring Security自动处理比对逻辑,开发者无需手动解密

第四章:深入处理登录成功与失败逻辑

4.1 自定义AuthenticationSuccessHandler实现登录后跳转

在Spring Security中,通过实现AuthenticationSuccessHandler接口可精确控制用户登录成功后的跳转逻辑,适用于多角色、多场景的动态跳转需求。
自定义处理器实现
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, 
                                        HttpServletResponse response, 
                                        Authentication authentication) throws IOException {
        String redirectUrl = "/default";
        if (authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))) {
            redirectUrl = "/admin/dashboard";
        } else if (authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_USER"))) {
            redirectUrl = "/user/home";
        }
        response.sendRedirect(redirectUrl);
    }
}
上述代码根据用户角色决定跳转路径。通过解析Authentication对象中的权限信息,动态设置重定向URL,避免了静态配置的局限性。
注册处理器到安全配置
  • 在HttpSecurity中通过.successHandler()方法注入自定义处理器
  • 确保原有默认行为被正确覆盖,同时处理会话或日志记录等附加逻辑

4.2 通过AuthenticationFailureHandler统一异常响应

在Spring Security中,认证失败后的响应流程可通过自定义`AuthenticationFailureHandler`进行统一管理,提升前后端交互的一致性与可维护性。
核心实现机制
通过实现`AuthenticationFailureHandler`接口,可重写`onAuthenticationFailure`方法,自定义失败时的响应逻辑:

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, 
                                       HttpServletResponse response,
                                       AuthenticationException exception) 
                                       throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"error\": \"Authentication failed\", \"message\": \"" 
                                   + exception.getMessage() + "\"}");
    }
}
上述代码将认证异常统一转换为JSON格式返回。`exception.getMessage()`捕获具体失败原因,如凭证错误或账户锁定,便于前端精准提示。
注册处理器
在安全配置中注入该处理器:
  1. 在HttpSecurity中调用.failureHandler()方法绑定实例;
  2. 确保异常不被默认页面跳转机制拦截。

4.3 实践:记录登录日志与失败次数限制策略

登录日志的结构化记录
为追踪用户行为并支持安全审计,系统需在每次登录尝试后生成结构化日志。日志应包含时间戳、IP地址、用户名、操作类型(成功/失败)等字段。
logEntry := map[string]interface{}{
    "timestamp": time.Now().UTC(),
    "ip":        clientIP,
    "username":  username,
    "event":     "login_attempt",
    "success":   isSuccess,
}
json.NewEncoder(logFile).Encode(logEntry)
该代码段将登录事件以JSON格式写入日志文件,便于后续通过ELK等工具进行集中分析与告警。
基于Redis的失败次数限流
为防止暴力破解,采用Redis临时计数器限制单位时间内的失败次数。使用IP或用户名作为键,设置滑动窗口过期时间。
  • 尝试登录失败 → 计数+1,TTL初始化为15分钟
  • 连续5次失败 → 拒绝后续请求直至冷却完成
  • 登录成功 → 立即清除计数器
此机制有效平衡安全性与用户体验,避免误封正常用户。

4.4 处理Ajax登录请求并返回JSON格式结果

在现代Web开发中,使用Ajax进行异步登录已成为主流做法。通过分离前端交互与后端验证逻辑,系统可实现无刷新认证并即时反馈结果。
请求处理流程
前端通过JavaScript发送POST请求至登录接口,携带用户名和密码。后端接收请求后执行身份校验,并以JSON格式返回响应。

$.ajax({
    url: '/login',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ username: 'admin', password: '123456' }),
    success: function(response) {
        if (response.success) {
            window.location.href = '/dashboard';
        } else {
            alert(response.message);
        }
    }
});
该脚本向/login端点提交JSON数据。若认证成功,跳转至仪表盘页面;否则提示错误信息。
后端响应结构
服务器应统一返回标准JSON格式,便于前端解析:
字段类型说明
successboolean认证是否成功
messagestring提示信息
tokenstring可选的JWT令牌

第五章:总结与高安全性登录的最佳实践建议

实施多因素认证(MFA)
在现代应用中,仅依赖密码已不足以保障账户安全。推荐使用基于时间的一次性密码(TOTP)或FIDO2安全密钥。例如,使用WebAuthn API实现无密码登录:

navigator.credentials.create({
  publicKey: {
    challenge: new Uint8Array([/* 服务器提供的挑战 */]),
    rp: { name: "MyApp" },
    user: {
      id: new Uint8Array([1,2,3]),
      name: "user@example.com",
      displayName: "John Doe"
    },
    pubKeyCredParams: [{ alg: -7, type: "public-key" }]
  }
}).then(cred => {
  // 将公钥凭证发送至服务器注册
});
强化密码存储策略
始终使用强哈希算法存储用户密码。推荐使用Argon2id或bcrypt,避免使用SHA-1或MD5。以下为Go语言中使用bcrypt的示例:

import "golang.org/x/crypto/bcrypt"

hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
    log.Fatal(err)
}
// 存储 hash 到数据库
会话管理最佳实践
采用短期JWT令牌结合HTTP-only、Secure标记的Cookie,并设置合理的过期时间。定期轮换刷新令牌,防止长期有效的会话被滥用。
配置项推荐值说明
AccessToken有效期15分钟减少泄露后的影响窗口
RefreshToken有效期7天需绑定设备并可撤销
Cookie属性HttpOnly, Secure, SameSite=Strict防御XSS和CSRF攻击
监控与异常响应
部署登录行为分析系统,检测高频失败尝试、异地登录等异常模式。结合IP信誉库与设备指纹技术,动态提升认证强度。
SpringSecurity详解,实现自定义登录接口 目前市面上比较流行的权限框架主要实Shiro和,这两个框架各自侧重点不同,各有各的优劣。要在自己写的页面手动调用登录接口同时还要进行附加操作。层不可能从内存中查询用户,需要跟实际的权限数据库关联。编写登录接口,在其中调用方法。该接口需要再未登录的情况下可调用,所以要放开权限。编写个的实现类,重写方法,在改方法中根据传来的用户名去自己的权限数据库查询用户信息。封装到用户实体类中。 阅读详情

相关推荐

Springboot +spring security,自定义认证器实现验证码功能

Springboot +spring security,自定义认证器实现验证码功能

weixin_40991408的博客 1083

Spring Security自定义登录

一、最关键的一个配置类 自定义一个SecurityConfig类继承自WebSecurityConfigurerAdapter抽象类,实现三个主要的方法: /** * 1.身份认证接口 */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).

qq_44188658的博客 4824

springboot3.x+springsecurity6.x多种方式登录验证

最新的 Spring Security 5.7 及以上版本,更新了不少内容,之前的 WebSecurityConfigurerAdapter 已经被废弃了,而且,要同时实现用户名密码登录、手机验证码登录、邮箱、微信小程序等登录方式,跟之前的配置方式都会有所不同。

程序猿的傻白甜 2192

权限框架SpringSecurity(一)——自定义登录

权限框架SpringSecurity(一)——自定义登录

scorpio的博客 1万+

AD9026芯片开发实战指南:从硬件配置到射频校准

本文为AD9026芯片开发实战指南,详细解析了从硬件设计、电源时钟配置、SPI初始化到多芯片同步与JESD204高速链路建立的完整流程。重点探讨了射频校准技术,包括初始化校准与跟踪校准,以保障5G、MIMO等现代通信系统所需的射频性能。旨在帮助开发者系统掌握这颗高性能射频收发器的应用,规避常见设计陷阱。

tomato的博客 853

从零开始:H20服务器上DeepSeek R1 671B大模型部署与压力测试全攻略

最近,我有幸在工作中接触到了DeepSeek R1 671B模型,这是目前中文开源领域参数量最大的高质量模型之一。DeepSeek团队在2024年推出的这款模型,以其惊人的6710亿参数量和出色的推理性能,引起了业界广泛关注。作为一名AI基础设施工程师,我有机会在H20服务器上部署这个庞然大物,并对其进行了全面的压力测试。这篇文章将详细记录我的部署过程和性能测试方法,希望能为大家提供一些参考。💡为什么选择DeepSeek R1?超大规模参数量(671B)优秀的中英文理解能力开源可商用的许可证。

wangli的博客 1万+

一文教会你SpringSecurity 自定义认证登录

现在登录方式越来越多,传统的账号密码登录已经不能满足我们的需求。可能我们还需要手机验证码登录,邮箱验证码登录,一键登录等。这时候就需要我们自定义我们系统的认证登录流程,下面,我就一步一步在SpringSecurity 自定义认证登录,以手机验证码登录为例

qq_36551991的博客 6460

STM32CubeIDE(CUBE-MX hal库)----RTC时钟断电保持与时间校准实战

本文详细介绍了在STM32CubeIDE中使用CUBE-MX和HAL库实现RTC时钟断电保持与时间校准的实战方法。通过硬件配置、后备寄存器(BKP)操作及软件校准策略,确保嵌入式设备在断电后仍能保持准确时间,适用于智能电表、环境监测等物联网应用场景。

weixin_29189373的博客 219

SpringSecurity之二:web自定义用户登录

官方文档:Hello Spring Security :: Spring Security 一、认证流程 先了解下SpringSecurity认证的流程,如下图(图片来自官网): step1:用户提交请求,AbstractAuthenticationProcessingFilter会从请求信息中生成Authentication对象,Authentication对象根据AbstractAuthenticationProcessingFilter子类决定; step2:通过Authentication.

铃萌的博客 2877

[CTFSHOW]JWT

文章目录前言JWT简介CTFSHOW Web345CTFSHOW Web346前置知识开始做题CTFSHOW Web347CTFSHOW Web348CTFSHOW Web349CTFSHOW Web350前置知识利用WP如何防御 前言 有些师傅向我咨询WP,索性就发了吧,其实早就写好了,只是懒,在github仓库里囤着 JWT简介 可以看看我的Github总结给自己看的,Y4tacker CTFSHOW Web345 首先打开题目,查看源码,接下来访问/admin被跳转回主页啥也没有发生 where is

Y4tacker的博客 6046

Labview程序框架介绍

当掌握LabVIEW基础知识并达到,理解单个小型模块程序会相对轻松。而若想进一步探索大型程序,就必然需要了解程序框架相关内容。LabVIEW常用的程序架构包括等。在多年工作中,我接触过的众多高级工程师所开发的大型程序,基本都基于这些架构搭建。接下来,将为大家详细介绍这些框架。

Misterlhw的博客 4624

Spring Security -- 自定义登录

Spring Security – 自定义登录 1 使用formLogin() http .formLogin() .loginPage("/myLogin") // 自定义登录页面 .loginProcessingUrl("/doLogin") // 自定义登录接口 .permitAll(); 2 自定义登录过滤器 SpringSecurity 默认使用的是 UsernamePasswordAuthenticationFilter 过滤器,我们可以实现 AbstractA

smile_code_dog的博客 2844

ARM SMMUv3设备树配置实战:从零开始为RK3588搭建IOMMU环境

本文详细介绍了在RK3588平台上配置ARM SMMUv3设备树的实战经验。从理解硬件架构、设备树节点定义,到内核驱动集成与调试,提供了完整的IOMMU环境搭建指南,并分享了解决StreamID冲突、中断配置等常见问题的技巧,帮助开发者高效完成控制器初始化。

l3m4n的博客 889

SpringSecurity自定义登录界面

为什么需要自定义登录界面? 答:因为SpringBoot整合SpringSecurity时,只需要一个依赖,无需其他配置,就可以实现认证功能。但是它的认证登录界面是固定那样的,如下图所示,但是我们希望自己搞个好看的登录界面,所以需要自定义登录界面。 第一步:创建springboot项目 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht

weixin_43472934的博客 7536

自动化上位机开发C#100例:如何用面向对象的方式封装雷赛运动控制卡EtherCAT总线卡(C#代码)

自动化上位机开发C#100例:雷赛运动控制卡EtherCAT总线卡C#封装类。

十多年IT经验,专注机器视觉,智能制造半导体行业 5036

自学 ABAP 和自学 SAP 的差别

有朋友在我的 ABAP 学习教程里留言: > 自学SAP是不是都要搭建虚拟服务器,然后自己去官网下载新版本SAP就可以吗 对于初学者,我们要搞清楚 ABAP 和 SAP 的区别。 ABAP 是一门编程语言,SAP 首先是德国软件公司的名称,也代表这家公司开发的一系列软件。SAP 公司开发的软件,我们有时也称产品,其功能能满足客户一个或者多个领域的业务需求。这些不同领域,我们也称为不同的业务模块,比如 ERP,CRM,SRM,HR 等等。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 6864

SpringSecurity(一)自定义登录界面

1. 新建一个SpringBoot工程 添加如下依赖 &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&g...

lizc_lizc的博客 6328

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Spring Security 实战:玩转自定义登录

1. 前言 前面的关于Spring Security相关的文章只是一个预热。为了接下来更好的实战,如果你错过了请从Spring Security 实战系列开始。安全访问的第一步就是认证(Authentication),认证的第一步就是登录。今天我们要通过对Spring Security的自定义,来设计一个可扩展,可伸缩的form登录功能。 2. form 登录的流程 下面是form登录的基本流程: 只要是form登录基本都能转化为上面的流程。接下来我们看看Spring ...

iqifenxia的博客 1005

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

SpringSecurity自定义登录

既然选择自定义登录,那么就要重新原本提供的默认登录接口(在使用jwt之前,无论是默认还是修改后的登录使用的都是cookie——session的方式)这里使用mybatis-plus查询数据,其他方式如jdbc,mybatis也都是可以的,顺便说一句plus真好用。

无人罪的博客 951

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SpringSecurity(02)——自定义登录和退出处理器

SpringSecurity自定义登录和退出处理器

peng_gx的博客 2034

SpringSecurity实现登录登出

SpringSecurity实现登录登出

qq_50909707的博客 3110

Spring Security实现多种登录方式

依赖导入<parent></parent>1.自定义MyUsernamePasswordFilter/*** 10:30*/@Slf4j// 自定拦截路由} else {// 获取登录表单= null?= null?@Nullable@Nullable/*** 获取登录用户信息* @return*/try {throw new NullPointerException("获取不到登录信息");

eugene03的博客 1842

SpringBoot + Spring Security多种登录方式:账号+微信网页授权登录

大家好,我是宝哥!一、概述实现账号用户名+微信网页授权登录集成在Spring Security的思路,最重要的一点是要实现微信登录通过Spring Security安全框架时,不需要验证账号、密码。二、准备工作要实现该功能,首先需要掌握Spring Security框架和微信扫码登录接口相关技术,如果对这两块还不太熟悉,可以参考:1、Springboot + Spring Security实现前后...

程序员闪充宝 4201

springsecurity OAuth2.0-第5章 springboot整合 spring security自定义登录页面

一 自定义认证页面 1.1 说明 1. 如果用户没有自定义登录页面,spring security 默认会启动自身内部的登录页面,尽管自动生成的登录页面很方便 快速启动和运行,但大多数应用程序都希望定义自己的登录页面。 1.2 自定义登录页面 在新建一个webapp目录,和resouces目录,平级,将login.jsp页面考配到这个页面下 页面代码: <%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-.

健康平安的活着的专栏 4586

springSecurity2的自定义账号密码认证流程+多个参数的自定义流程

本文包含了,两个参数的登录校验+多个参数的登录校验

m0_56356631的博客 4866
上一篇: 【企业级开发效率提升300%】:Spring Boot 3整合MyBatis-Plus最佳实践曝光
下一篇: C语言高手必修课(指针数组 vs 数组指针全剖析)
LiteCode
博客等级 码龄1年 146粉丝 2019原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值