簡體   English   中英

ReactJS / Spring 啟動 email 確認請求參數

[英]ReactJS / Spring Boot email confirmation request parameter

我有一個登錄和注冊表單,注冊后用戶會收到一個 email 以確認他們的帳戶,然后才能登錄。

我正在使用 Spring 引導和 email 鏈接將用戶帶到我的 /confirm REST 端點,該端點將生成唯一令牌並允許他們確認用戶帳戶(啟用它們)。

如果我嘗試像 http://localhost:3000/confirm/"+confirmationToken 一樣將鏈接設置到我的前端,它會重定向我,但實際上並沒有確認帳戶。

我正在努力理解的問題是如何防止 email 鏈接將用戶帶到 spring 引導端點並將它們發送到 React 路由並通過調用我擁有的 /confirm 端點來確認帳戶。

目前這就是我所擁有的。


電子郵件服務.java

  • 負責發送 email 以及將用戶帶到我的反應路線的鏈接(但這實際上並沒有啟用他們的帳戶),這是我無法弄清楚的。
@Service
public class EmailService {

    private final static Logger LOGGER = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private JavaMailSender mailSender;

    public void sendMail(String email, String confirmationToken){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(email);
        mailMessage.setSubject("Account Activation!");
        mailMessage.setText("To confirm your account, please click here : "
                +"http://localhost:3000/confirm/"+ confirmationToken
                + "   Note: This link will expire after 10 minutes.");
        mailSender.send(mailMessage);
    }
}

AuthController.java

  • /register 端點創建一個用戶,但他們的帳戶被禁用
  • /confirm 檢查鏈接是否仍然有效(10 分鍾)並確認用戶帳戶。
 @PostMapping("/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody User user, BindingResult result) {
        // validation
        userValidator.validate(user, result);
        ResponseEntity<?> errorMap = errorValidationService.validationService(result);
        if(errorMap != null) return errorMap;

        // the email confirmation token
        userService.saveUser(user);

        ConfirmationToken confirmationToken = userService.createToken(user);
        emailService.sendMail(user.getEmail(), confirmationToken.getConfirmationToken());

        URI location = ServletUriComponentsBuilder.fromCurrentContextPath().path("/api/test/user").buildAndExpand(user.getId()).toUri();

        return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully! Please check your email for a verification link < " + user.getEmail() + " >"));
    }



    @GetMapping("confirm")
    public ResponseEntity<?> getMethodName(@RequestParam("token") String token) {

        ConfirmationToken confirmationToken = userService.findByConfirmationToken(token);

        if (confirmationToken == null) throw new InvalidTokenException("Invalid token");

        User user = confirmationToken.getUser();
        Calendar calendar = Calendar.getInstance();

        if((confirmationToken.getExpiredAt().getTime() - calendar.getTime().getTime()) <= 0) {
            return ResponseEntity.badRequest().body("Link expired. Generate new link from http://localhost:3000/signin");
        }

        user.setEmailVerified(true);

        userService.save(user);
        return ResponseEntity.ok("Account verified successfully!");
    }

在我的前端,我有這些路線

應用程序.js

    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/signin" element={<Login />} />
        <Route path="/signup" element={<SignUp />} />

        <Route path="/confirm/:token" element={<EmailConfirmedComponent />} />
        
        <Route path="*" element={<NotFound />} />
      </Routes>
    </Router>

EmailConfirmedComponent.js

import React, {useState, useEffect} from 'react'
import { Link } from 'react-router-dom';

const EmailConfirmedComponent = () => {

    return (
        <div style={{margin: "2rem"}}>
            <h1>Thank you for creating an account!</h1>

            <Link to="/signin">
             <button className="btn btn-primary">Go to login</button>
            </Link>

        </div>
    )
}

export default EmailConfirmedComponent;

我建議不要將服務 URI 與客戶端 URL 混合,無論如何部署這兩個項目都不會遇到這種情況。

解決方案:

email 可以繼續將 URL 顯示為'http://<hostname>/confirm/' + confirmationToken confirmToken 。

更改EmailConfirmedComponent ,使其使用特定 URI 對您的服務進行 REST 調用,以創建帳戶。

您的服務 URI 應以自定義服務上下文路徑開頭,以避免與 UI 路由沖突。 例如localhost:3000/my-service/confirm

為此,請將以下內容添加到您的服務application.properties文件中:

server.servlet.contextPath=/my-service

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM