《web应用技术》第十次课后练习

后端 - Spring Security 配置

package com.movie.api.config;

import org.springframework.context.annotation.Bean;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用内存中的用户进行演示
        auth.inMemoryAuthentication()
            .withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN")
            .and()
            .withUser("user").password(passwordEncoder().encode("password")).roles("USER");
        // 其他配置...
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // 禁用 CSRF 保护(实际项目中需要谨慎处理)
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN") // 只有管理员可以访问 /admin/**
                .antMatchers("/user/**").hasAnyRole("USER", "ADMIN") // 用户和管理员都可以访问 /user/**
                .antMatchers("/", "/login", "/register").permitAll() // 允许所有人访问登录和注册页面
                .anyRequest().authenticated() // 其他所有请求都需要认证
            .and()
            .formLogin() // 表单登录配置
                .loginPage("/login") // 自定义登录页面
                .permitAll() // 允许所有人访问登录页面
            .and()
            .logout() // 注销配置
                .permitAll(); // 允许所有人发起注销请求
    }
}

前端 - 登录页面

<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Page</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2 class="mt-5">Login</h2>
        <form action="/login" method="post">
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" class="form-control" id="username" name="username" required>
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control" id="password" name="password" required>
            </div>
            <button type="submit" class="btn btn-primary">Login</button>
        </form>
    </div>
</body>
</html>

后端 - 登录逻辑

// ... 其他代码保持不变 ...

@PostMapping("/login")
@ApiOperation("管理员登陆")
public ResponseEntity<?> login(@RequestBody LoginDto loginDto, HttpServletResponse response) throws Exception {
    HashMap<String, String> map = new HashMap<>();
    String token = adminService.login(loginDto);
    if (token != null) {
        map.put("token", token);
        response.addHeader("Authorization", "Bearer " + token);
        return ResponseEntity.ok(map);
    } else {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Login Failed");
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值